toString and valueOf truncates trailing 0s after decimal

后端 未结 2 1837
南旧
南旧 2021-01-13 18:27

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         


        
相关标签:
2条回答
  • 2021-01-13 18:54

    It is not toString nor valueOf that truncates trailing 0s after a decimal!
    When you write a decimal this way:

    var num2 = 0.0100
    

    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
    

    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.

    0 讨论(0)
  • 2021-01-13 19:16

    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-

    var n= '0.0'
    alert(n)>> 0
    alert(n.toFixed(5))>> '0.00000'
    alert(n.toPrecision(5))>>'0.0000'
    
    0 讨论(0)
提交回复
热议问题