ToString and valueOf truncate the final 0 s after the decimal

In javascript, I noticed that toString and valueOf truncate trailing 0s after the decimal number. For instance:

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 common behavior and is there a way to keep trailing 0s?

EDIT: I changed my original question because after some tests I realized that the above is the root of the problem. Thanks.

+4
source share
2 answers

This is not toString and valueOf , which truncates trailing 0s after the decimal number!
When you write a decimal as follows:

 var num2 = 0.0100 

you tell your interpreter that the variable num2 should contain the decimal number 0.0100, i.e. 0.01, since the last two zeros are not significant.
A decimal number is a memory represented as a decimal number:

 0.0100 0.010 0.01 0.01000 

- all are the same number, and therefore they are all represented equally in memory. They cannot be distinguished.
Thus, it is impossible to find out if num2 is assigned a value of 0.01 by writing this number with zero, one, two or more trailing zeros.

If you want to save the decimal number as it is written, you must save it as a string.

+4
source

A number in javascript has no trailing zeros - if possible, where would you stay? This is normal behavior. You can make them appear if you return the string

 var n= '0.0' alert(n)>> 0 alert(n.toFixed(5))>> '0.00000' alert(n.toPrecision(5))>>'0.0000' 
+2
source

Source: https://habr.com/ru/post/1310398/


All Articles