I have the following dummy test script:
(我有以下虚拟测试脚本:)
function test() { var x = 0.1 * 0.2; document.write(x); } test();
This will print the result 0.020000000000000004
while it should just print 0.02
(if you use your calculator).
(这将打印结果0.020000000000000004
而应该只打印0.02
(如果使用计算器)。)
As far as I understood this is due to errors in the floating point multiplication precision.(据我了解,这是由于浮点乘法精度的错误。)
Does anyone have a good solution so that in such case I get the correct result 0.02
?
(有没有人有一个好的解决方案,这样在这种情况下我可以得到0.02
的正确结果?)
I know there are functions like toFixed
or rounding would be another possibility, but I'd like to really have the whole number printed without any cutting and rounding.(我知道还有诸如toFixed
或四舍五入之类的函数是另一种可能性,但是我真的想在不进行任何舍入和四舍五入的情况下真正打印出整个数字。)
Just wanted to know if one of you has some nice, elegant solution.(只是想知道你们中的一个人是否有一些不错的,优雅的解决方案。)
Of course, otherwise I'll round to some 10 digits or so.
(当然,否则我将四舍五入到十位数左右。)
ask by Juri translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…