Remove insignificant trailing zeros from a number?

Have I missed a standard API call that removes trailing insignificant zeros from a number?

Ex.

var x = 1.234000 // to become 1.234;
var y = 1.234001; // stays 1.234001

Number.toFixed() and Number.toPrecision() are not quite what I'm looking for.


如果将其转换为字符串,它将不会显示任何尾随零,这些尾随零并不存储在变量中,因为它是作为数字创建的,而不是字符串。

var n = 1.245000
var noZeroes = n.toString() // "1.245" 

I had a similar instance where I wanted to use .toFixed() where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.

toFixed without padding

parseFloat(n.toFixed(4));

Another option that does almost the same thing
This answer may help your decision

Number(n.toFixed(4));

toFixed will truncate/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:

var n = "1.234000";
    n = parseFloat(n);
 // n is 1.234 and in number form

Because even if you define a number with trailing zeros they're dropped.

var n = 1.23000;
 // n == 1.23;

I first used a combination of matti-lyra and gary's answers:

r=(+n).toFixed(4).replace(/.0+$/,'')

Results:

  • 1234870.98762341: "1234870.9876"
  • 1230009100: "1230009100"
  • 0.0012234: "0.0012"
  • 0.1200234: "0.12"
  • 0.000001231: "0"
  • 0.10001: "0.1000"
  • "asdf": "NaN" (so no runtime error)
  • The somewhat problematic case is 0.10001. I ended up using this longer version:

        r = (+n).toFixed(4);
        if (r.match(/./)) {
          r = r.replace(/.?0+$/, '');
        }
    
  • 1234870.98762341: "1234870.9876"
  • 1230009100: "1230009100"
  • 0.0012234: "0.0012"
  • 0.1200234: "0.12"
  • 0.000001231: "0"
  • 0.10001: "0.1"
  • "asdf": "NaN" (so no runtime error)
  • Update : And this is Gary's newer version (see comments):

    r=(+n).toFixed(4).replace(/([0-9]+(.[0-9]+[1-9])?)(.?0+$)/,'$1')
    

    This gives the same results as above.

    链接地址: http://www.djcxy.com/p/77456.html

    上一篇: 如何很好地将浮动数字格式化为字符串而不使用不必要的小数0

    下一篇: 从数字中删除无用的尾随零?