javascript Lodash 舍入精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32336056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:08:04  来源:igfitidea点击:

Lodash rounding precision

javascriptroundingpercentagelodashfloating-point-precision

提问by Tim Perkins

I'm trying to display a number as a percent by using _.roundand then by multiplying the number by 100. For some reason, when I multiply the rounded number, the precision gets messed up. Here's what it looks like:

我试图通过使用_.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

小提琴

Why is the 0.000000000000001 added to the number after multiplying by 100?

为什么乘以100后的数字加上0.000000000000001?

回答by Benny Bottema

This is due to the fact that numbers are represented internally as binary numbers with limited precision.

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

See also "Is floating point math broken?"

另请参阅“浮点数学是否已损坏?”



Is floating point math broken?

浮点数学被破坏了吗?

0.1 + 0.2 == 0.3 -> false

0.1 + 0.2 -> 0.30000000000000004

Any ideas why this happens?

0.1 + 0.2 == 0.3 -> 假

0.1 + 0.2 -> 0.30000000000000004

任何想法为什么会发生这种情况?

Which got the answer:

得到了答案:

Binary floating pointmath 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.

二进制浮点数学就是这样。在大多数编程语言中,它基于IEEE 754 标准。JavaScript 使用 64 位浮点表示,这与 Java 的double. 问题的关键是数字以这种格式表示为整数乘以 2 的幂;分母不是 2 的幂的有理数(例如0.1, which is 1/10)无法精确表示。



To get the correct outcome in your case, you need to round afterall the arithmetic:

为了得到正确的结果,你的情况,你需要一轮所有的算术:

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

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