JavaScript乘法不正确,导致舍入不正确 [英] Javascript multiplying incorrectly, causing incorrect rounding

查看:127
本文介绍了JavaScript乘法不正确,导致舍入不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我提取要乘的值时,它们是字符串.因此,我将它们拉出,将它们解析为浮点数(以保留小数位),然后将它们相乘.

When I pull the values I want to multiply, they're strings. So I pull them, parse them as floats (to preserve the decimal places), and multiply them together.

LineTaxRate = parseFloat(myRate) * parseFloat(myQuantity) * parseFloat(myTaxRateRound);

这已处理了我99%的发票,但是我发现了一个非常奇怪的问题.

This has worked for 99% of my invoices but I discovered one very odd problem.

乘以时: 78 * 7 * 0.0725

JavaScript正在返回: 39.584999999999994

Javascript is returning: 39.584999999999994

通常情况下,您可以在计算器中进行数学运算: 39.585

When you normally do the math in a calculator its: 39.585

说完所有内容后,我将这个数字取整并使用 .toFixed(2)

When all is said and done, I take that number and round it using .toFixed(2)

由于Javascript返回了该数字,因此无法将其舍入到所需的值: $ 39.59

Because Javascript is returning that number, it's not rounding to the desired value of: $39.59

我尝试了总计 Math.round(),但我仍然得到相同的数字.

I tried Math.round() the total but I still get the same number.

我曾考虑过将数字四舍五入到小数点后3位,再加上2位,但这对我来说似乎很棘手.

I have thought of rounding the number to 3 decimals then two, but that seems hacky to me.

我到处搜索,我看到的是人们提到parseFloat失去了它的精度,并使用.toFixed,但是在上面的示例中,这没有帮助.

I have searched everywhere and all I see is people mention parseFloat loses its precision, and to use .toFixed, however in the example above, that doesn't help.

这是我用来重现问题的测试脚本:

Here is my test script i made to recreate the issue:

<script>
var num1 = parseFloat("78");
var num2 = parseFloat("7");
var num3 = parseFloat("0.0725");
var myTotal = num1 * num2 * num3;
var result = Math.round(myTotal*100)/100

alert(myTotal);
alert(myTotal.toFixed(2));
alert(result);
</script>

推荐答案

浮点数以二进制而不是十进制表示.某些十进制数字将无法精确表示.而且不幸的是,由于Javascript只具有一个Number类,因此它并不是一项很好的工具.其他语言也有适当的十进制库,旨在避免这种错误.您将不得不接受一个美分的错误,在服务器端实现一个解决方案,或者非常努力地解决此问题.

Floating points are represented in binary, not decimal. Some decimal numbers will not be represented precisely. And unfortunately, since Javascript only has one Number class, it's not a very good tool for this job. Other languages have decent decimal libraries designed to avoid precisely this kind of error. You're going to have to either accept one-cent errors, implement a solution server-side, or work very hard to fix this.

哦!您可以执行78 * 7 * 725,然后除以10000,或者更精确地说,只要将小数点放在正确的位置即可.基本上将税率表示为一小部分.不太方便,但可能会解决您的乘法错误.

edit: ooh! you can do 78 * 7 * 725 and then divide by 10000, or to be even more precise just put the decimal point in the right place. Basically represent the tax rate as something other than a tiny fraction. Less convenient but it'll probably take care of your multiplication errors.

这篇关于JavaScript乘法不正确,导致舍入不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆