Java 脚本 parseFloat() 意外的小数位

Java Script parseFloat() unexpected decimal places

提问人:A.Polieshchuk 提问时间:6/2/2022 更新时间:6/2/2022 访问量:279

问:

为什么当我将此字符串“2019275.159999999916180968”转换为数字或使用parseFloat(str)时。我总是得到结果“2019275.16”。为什么它会删除字符串中提供的额外小数位?在这种情况下,我怎样才能保留小数位数,而不将其四舍五入到小数点后 2 位?

字符串中的小数位数是动态的。

JavaScript 节点 .js 浮点

评论

0赞 Barmar 6/2/2022
因为浮点数没有那么高的精度,而且在它所具有的精度水平上,这两个数字是等效的。
0赞 A.Polieshchuk 6/2/2022
但是在解析后,我使 2019275.16.toFixed(18) 我得到了与我需要完全相同的值 - “2019275.1599999999916180968”。那么为什么它不能一下子成功呢?
0赞 adevinwild 6/2/2022
嗨,尝试使用这个:developer.mozilla.org/docs/Web/JavaScript/Reference/...
0赞 Barmar 6/2/2022
因为当您不使用 指定精度时,它使用产生等效内部表示的最小精度。toFixed()
0赞 Barmar 6/2/2022
2019275.159999999916180968 == 2019275.16是。true

答:

0赞 noroot 6/2/2022 #1

您可以在 parseFloat() 之后使用 toFixed() 方法,否则它将返回等效于内部表示的最小精度

parseFloat("2019275.159999999916180968").toFixed(18)

评论

2赞 Ben Stephens 6/2/2022
parseFloat(“2019275.159999999912345678”).toFixed(18) 也是 “2019275.159999999916180968”
0赞 A.Polieshchuk 6/2/2022
那么,我们是否有办法存储“2019275.159999999912345678”(例如)转换后的所有小数位
1赞 Ben Stephens 6/2/2022 #2

可能值得研究像 decimal.js 这样的库来帮助解决这个问题。例如:

Decimal.set({ precision: 24 }); // The default of 20 is not big enough for the number below so you may need to adjust this

let a = new Decimal('2019275.159999999912345');
a = a.plus(1);

let b = new Decimal('2019275.159999999912345').plus(1);
let c = Decimal.add('2019275.159999999912345', 1);

console.log(a, b, c);
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/9.0.0/decimal.min.js"></script>