Tutorial :toString and valueOf truncates trailing 0s after decimal



Question:

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.


Solution:1

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.


Solution:2

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'  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »