toString 和 valueOf 截断小数点后的尾随 0
在 javascript 中,我注意到 toString 和 valueOf 截断了小数点后的尾随 0。例如:
var num = 0.00
var num2 = 0.0100
num.valueOf() or num.toString() // outputs 0
num2.valueOf() or num2.toString() // outputs 0.01
这是正常行为吗?是否有办法保留尾随的 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
Is this normal behavior and is there someway to retain the trailing 0s?
EDIT: I changed my original question because I realized after some testing that the above is root of the problem. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
toString
和valueOf
都不会截断小数点后的尾随 0!当您这样写小数时:
您告诉解释器变量 num2 应包含小数 0.0100,即 0.01,因为最后两个零不重要。
十进制数在内存中表示为十进制数:
都是完全相同的数字,因此它们在内存中的表示方式相同。无法区分它们。
因此不可能知道 num2 值 0.01 是否已分配给该数字并带有零、一个、两个或多个尾随零。
如果您想按照书写方式存储十进制数,则必须将其存储为字符串。
It is not
toString
norvalueOf
that truncates trailing 0s after a decimal!When you write a decimal this way:
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:
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.
JavaScript 中的数字没有尾随零 -
如果可以的话,你会在哪里停下来?
这是正常行为。
如果您返回一个字符串,您可以强制它们出现 -
A number in javascript does not have trailing zeros-
if it could, where would you stop?
That is normal behavior.
You can force them to appear if you return a string-