Remove insignificant trailing zeros from a number?
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 round/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;
If you convert it to a string it will not display any trailing zeros, which aren't stored in the variable in the first place since it was created as a Number, not a String.
var n = 1.245000
var noZeroes = n.toString() // "1.245"
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.
The toFixed
method will do the appropriate rounding if necessary. It will also add trailing zeroes, which is not always ideal.
(4.55555).toFixed(2);
//-> "4.56"
(4).toFixed(2);
//-> "4.00"
If you cast the return value to a number, those trailing zeroes will be dropped. This is a simpler approach than doing your own rounding or truncation math.
+(4.55555).toFixed(2);
//-> 4.56
+(4).toFixed(2);
//-> 4
How about just multiplying by one like this?
var x = 1.234000*1; // becomes 1.234
var y = 1.234001*1; // stays as 1.234001