Add trailing zeros to an integer without convertin

2020-05-09 17:20发布

问题:

I'm looking to add decimals to the end of my integer. As an example:

15 => 15.00

The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.

Is this possible? If not, can someone explain to me the logic behind why this isn't possible?

EDIT: Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701

回答1:

The problem you are finding is that all numbers in javascript are floats.

a = 0.1
typeof a # "number"

b = 1
typeof b # number

They are the same.

So there is no real way to convert to from an integer to a float.

This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.

Depending on your exact use case you will need to use strings if you want to display with a defined precision.



回答2:

When working with numbers 15 and 15.00 are equal. It wouldn't make any sense to use memory to store those trailing or leading zeros. If that information is needed it is usually for displaying purposes. In that case a string is the right choice. In case you need that value again you can parse the string as a number.