javascriptnumbers

Add trailing zeros to an integer without converting to string in JS?


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


Solution

  • 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.