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

后端 未结 2 1507
礼貌的吻别
礼貌的吻别 2021-01-28 05:50

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.

相关标签:
2条回答
  • 2021-01-28 06:28

    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.

    0 讨论(0)
  • 2021-01-28 06:32

    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.

    0 讨论(0)
提交回复
热议问题