JavaScript乘以100会导致奇怪的结果

29

我有:

var a =  0.0532;
var b =  a * 100;
b应该返回5.32,但实际上它返回了5.319999999999999。如何修复?

JSFiddle在这里: http://jsfiddle.net/9f2K8/


以下是解决方案:function moveComma(val, moveCommaByInput) { if (val || typeof val === 'number') { const valueNumber = Number(val); const moveCommaBy = moveCommaByInput || 0; if (isNaN(valueNumber)) { return null; } else { return Number(`${valueNumber}e${moveCommaBy}`); } } return null; } - Jacek Koziol
我已经通过var b = a * 1000 / 10;解决了这个问题。 - undefined
2个回答

20

你应该使用.toFixed()

示例

var a =  0.0532;
var b =  a * 100;
b.toFixed(2);     //specify number of decimals to be displayed

我不确定将数字“2”作为“.toFixed”函数的参数是否安全。如果a=0.53245239934或b=10呢? - Mulan
如果 a = 0.53245239934,则返回 0.53,并且对于 b 返回 10.00 - yashhy
我只是想说,您可能不希望做出这样的假设,即“2”是一个可接受的精度,仅因为在此特定情况下不会丢失数据。 - Mulan
1
Number.prototype.toFixed是一个用于格式化数字的函数。它返回一个字符串。如果你需要一个数字而不是一个字符串,请查看这个答案https://dev59.com/-3E95IYBdhLWcg3whODK#29494612。 - Ed Spencer

13

这不是一个错误。

Javascript试图尽可能精确地表示数字5.32。由于计算机没有无限的精度,它会选择最接近的数字:5.319999999999999

如果您遇到数字运算问题,您应该能够轻松地进行加法、乘法等运算。它们非常接近所需数字,因此结果将在可以忽略不计的误差范围内。

如果您的问题与比较数字有关,通常的做法是舍弃==,而是使用定义好的误差范围进行比较。例如:

// Two previously obtained instances of the "same" number:
a = 5.32
b = 5.319999999999999

// Don't do this:
if (a == b) {}

// Do this instead (hide it in a function):
margin = 0.000001
if (Math.abs(a - b) < margin) {}

如果您的问题是可视化的,您可以使用toFixed()来创建一个四舍五入的易于阅读的字符串:
number = 123.4567
number.toFixed(2)
> '123.46'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接