Converting number into string in JavaScripts without trailing zeros from number

前端 未结 2 1520
星月不相逢
星月不相逢 2021-01-26 11:53

I tried to convert number to string in JavaScripts using toString() but it truncates insignificant zeros from numbers. For examples;

var n1 = 250.00 
var n2 = 59         


        
相关标签:
2条回答
  • 2021-01-26 12:12

    The number doesn't know how many trailing 0 there are because they are not stored. In math, 250, 250.00 or 250.0000000000000 are all the same number and are all represented the same way in memory.

    So in short, there is no way to do what you want. What you can do is format all numbers in a specific way. See Formatting a number with exactly two decimals in JavaScript.

    0 讨论(0)
  • 2021-01-26 12:21

    As far as I know, you can't store number with floating zeros, but you can create zeroes with floating zeroes, by using toFixed:

    var n1 = 250;
    var floatedN1 = n1.toFixed(2); //type 'string' value '250.00'
    
    0 讨论(0)
提交回复
热议问题