简体   繁体   中英

How can I use Number() to convert a string to number without losing the decimal points?

I tried

num = 0.5;
num =  Number(num.toPrecision(2));

I want the result to be 0.50, but it's returning 0.5.

The .toPrecision() method returns a string representation of a number. If you pass that to Number() , it parses it as a number and you get a number value as a result. The number 0.5 and the number 0.50 are precisely equal; when you print or log the number 0.5 you don't get any extra digits because that's just how the default string conversion of numbers works. That, in fact, is the reason .toPrecision() exists.

The nature of JavaScript numbers is such that it just doesn't make sense to want to retain trailing fractional zero digits. Numbers are binary floating point values internally, so trailing decimal fractional digits have no place.

When you're dealing with a Number , both 0.5 and 0.50 are identical and thus stored the same in the RAM. JavaScript has no way to differentiating between them.

However, .toPrecision() returns a String , which can differentiate between "0.05" and "0.5" , as they're two different String s where the first is 4 bytes long and the second is 3 bytes long

So basically , if you want to output 0.50 , then just use .toPrecision() and do not convert it back to Number .


 0.5  ==  0.50
"0.5" != "0.50"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM