提问人:A.Polieshchuk 提问时间:6/2/2022 更新时间:6/2/2022 访问量:279
Java 脚本 parseFloat() 意外的小数位
Java Script parseFloat() unexpected decimal places
问:
为什么当我将此字符串“2019275.159999999916180968”转换为数字或使用parseFloat(str)时。我总是得到结果“2019275.16”。为什么它会删除字符串中提供的额外小数位?在这种情况下,我怎样才能保留小数位数,而不将其四舍五入到小数点后 2 位?
字符串中的小数位数是动态的。
答:
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>
评论
toFixed()
2019275.159999999916180968 == 2019275.16
是。true