Limit the amount of number shown after a decimal place in javascript
Warning! The currently accepted solution fails in some cases, e.g. with 4.27 it wrongly returns 4.26.
Here is a general solution that works always.
(Maybe I should put this as a comment, but at the time of this writing, I don't have the required reputation)
If you don't want rounding to 2 decimal places, use toFixed()
to round to n decimal places and chop all those off but 2:
var num = 4.3455.toFixed(20);
alert(num.slice(0, -18));
//-> 4.34
Note that this does have the slight downside of rounding when the number of decimal places passed to toFixed()
is less than the number of decimal places of the actual number passed in and those decimal places are large numbers. For instance (4.99999999999).toFixed(10)
will give you 5.0000000000
. However, this isn't a problem if you can ensure the number of decimal places will be lower than that passed to toFixed()
. It does, however, make @TJ's solution a bit more robust.
You're looking for toFixed
:
var x = 4.3455;
alert(x.toFixed(2)); // alerts 4.35 -- not what you wanted!
...but it looks like you want to truncate rather than rounding, so:
var x = 4.3455;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(2)); // alerts 4.34
As T.J answered, 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.
+parseFloat((4.55555).toFixed(2));
//-> 4.56
+parseFloat((4).toFixed(2));
//-> 4