JavaScript: Round to a number of decimal places, but strip extra zeros
Here's the scenario: I'm getting .9999999999999999
when I should be getting 1.0
.
I can afford to lose a decimal place of precision, so I'm using .toFixed(15)
, which kind of works.
The rounding works, but the problem is that I'm given 1.000000000000000
.
Is there a way to round to a number of decimal places, but strip extra whitespace?
Note: .toPrecision
isn't what I want; I only want to specify how many numbers after the decimal point.
Note 2: I can't just use .toPrecision(1)
because I need to keep the high precision for numbers that actually have data after the decimal point. Ideally, there would be exactly as many decimal places as necessary (up to 15).
Solution 1:
>>> parseFloat(0.9999999.toFixed(4));
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0
Solution 2:
Yes, there is a way. Use parseFloat()
.
parseFloat((1.005).toFixed(15)) //==> 1.005
parseFloat((1.000000000).toFixed(15)) //==> 1
See a live example here: http://jsfiddle.net/nayish/7JBJw/
Solution 3:
As I understand, you want to remove the trailing zeros in the string that you obtained via toFixed()
. This is a pure string operation:
var x = 1.1230000;
var y = x.toFixed(15).replace(/0+$/, ""); // ==> 1.123
Solution 4:
Number(n.toFixed(15)) or +(n.toFixed(15))
will convert the 15 place decimal string to a number, removing trailing zeroes.
Solution 5:
If you cast the return value to a number, those trailing zeroes will be dropped. This is also less verbose than parseFloat()
is.
+(4.55555).toFixed(2);
//-> 4.56
+(4).toFixed(2);
//-> 4
This uses the unary + operator, so if using this as part of a string operation you need to have an infix + before it: var n=0.9999999999999999; console.log('output ' + +n.toFixed(2));
. FYI a unary + in front of a string converts it to a Number. From MDN: Unary + can:
convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.