[英]Useless decimals in calculation
Might somebody already faced with calculation issue like in snippet below.可能有人已经面临以下代码段中的计算问题。 First console command shows useless digits after calculation 10.1 +20.1 should be 30.2 but calculated as 30.200000000000003.
第一个控制台命令在计算后显示无用数字 10.1 +20.1 应该是 30.2 但计算为 30.200000000000003。 and second one 10.2 + 20.2=30.4 is correct.
第二个 10.2 + 20.2=30.4 是正确的。 There can be a lot of such decimal pairings which creates additional decimals in summ.
可能有很多这样的小数配对,它们会在总和中创建额外的小数。 Why does it happends and hove to avoid it?
为什么它会发生并且必须避免它?
console.log(10.1 + 20.1); console.log(10.2 + 20.2);
This looks like a duplicate of How to deal with floating point number precision in JavaScript?这看起来像是如何处理 JavaScript 中的浮点数精度的副本? .
.
You can use.toFixed(2) to always get a number with only 2 decimals.您可以使用 .toFixed(2) 始终获得只有 2 位小数的数字。 https://www.w3schools.com/jsref/jsref_tofixed.asp
https://www.w3schools.com/jsref/jsref_tofixed.asp
More info: https://www.w3schools.com/js/js_numbers.asp更多信息: https://www.w3schools.com/js/js_numbers.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.