Lodash 舍入精度

Lodash rounding precision

我试图通过使用 _.round 然后将该数字乘以 100 来将数字显示为百分比。出于某种原因,当我将四舍五入的数字相乘时,精度变得一团糟。这是它的样子:

var num = 0.056789,
    roundingPrecision = 4,
    roundedNum = _.round(num, roundingPrecision),
    percent = (roundedNum * 100) + '%';

console.log(roundedNum); // 0.0568
console.log(percent); // 5.680000000000001%

fiddle

为什么乘以100后会加上0.000000000000001?

这是因为数字在内部表示为精度有限的二进制数。

另见 "Is floating point math broken?"


浮点数学是不是坏了?

0.1 + 0.2 == 0.3 -> false

0.1 + 0.2 -> 0.30000000000000004

Any ideas why this happens?

得到答案的是:

Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.


为了在您的案例中获得正确的结果,您需要在 之后对所有算术进行舍入

var num = 0.056789,
  roundingPrecision = 4,
  roundedNum = _.round(num * 100, roundingPrecision),
  percent = roundedNum + '%';

console.log(percent); // 5.6789%
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script>