Hay, i have some floats like these
4.3455
2.768
3.67
and i want to display them like this
4.34
2.76
3.67
I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.
Hay, i have some floats like these
4.3455
2.768
3.67
and i want to display them like this
4.34
2.76
3.67
I don't want to round the number up or down, just limit the amount of numbers shown after the decimal place to 2.
Use toPrecision :)
The 2 in the second line dictates the number of decimal places, this approach returns a number, if you want a string remove the "+" operator.
You're looking for
toFixed
:...but it looks like you want to truncate rather than rounding, so:
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: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 you5.0000000000
. However, this isn't a problem if you can ensure the number of decimal places will be lower than that passed totoFixed()
. It does, however, make @TJ's solution a bit more robust.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)
Good news everyone! Since a while there is an alternative: toLocaleString()
While it isn't exactly made for rounding, there is some usefuls options arguments.
minimumIntegerDigits
minimumFractionDigits
maximumFractionDigits
minimumSignificantDigits
maximumSignificantDigits
Example usage:
But this does not match the question, it is rounding:
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.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.