Remove insignificant trailing zeros from a number?

2019-01-04 00:24发布

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.

13条回答
戒情不戒烟
2楼-- · 2019-01-04 01:12

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.

查看更多
登录 后发表回答