toString和valueOf截断小数点后0 [英] toString and valueOf truncates trailing 0s after decimal
问题描述
在javascript中,我注意到toString和valueOf会在小数点后截尾0.例如:
In javascript, I've noticed that toString and valueOf truncates trailing 0s after a decimal. For example:
var num = 0.00
var num2 = 0.0100
num.valueOf() or num.toString() // outputs 0
num2.valueOf() or num2.toString() // outputs 0.01
这是正常行为吗,是否有办法保留尾随0?
Is this normal behavior and is there someway to retain the trailing 0s?
我更改了最初的问题,因为经过一些测试,我意识到上面是问题的根源.谢谢.
I changed my original question because I realized after some testing that the above is root of the problem. Thanks.
推荐答案
不是 toString
也不是 valueOf
会在小数点后截尾0!当您以这种方式写小数时:
It is not toString
nor valueOf
that truncates trailing 0s after a decimal!
When you write a decimal this way:
var num2 = 0.0100
您告诉您的解释器变量 num2 应该包含十进制数字0.0100,即0.01,因为最后两个零并不重要.
十进制数是用十进制数表示的内存:
you are telling your interpreter that variable num2 should contain decimal number 0.0100, i.e. 0.01 since the last two zeros are not significant.
The decimal number is memory represented as a decimal number:
0.0100
0.010
0.01
0.01000
都是相同的数字,因此它们在内存中的表示方式相同.无法区分它们.
因此,不可能知道是否已为 num2 值0.01分配了写入该数字的零,一,两个或多个尾随零.
are all the very same number and so they are all represented the same way in memory. It is not possible to distinguish among them.
So it is not possible to know if num2 value 0.01 has been assigned writing that number with zero, one, two or more trailing zeros.
如果要以十进制数字的方式存储小数,则必须将其存储为字符串.
If you want to store a decimal number the way it is written then you have to store it as a string.
这篇关于toString和valueOf截断小数点后0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!