How can i get just 2 digits after comma in javascript? For example, 0.34 instead of 0.3445434.
+5
A:
var result = Math.round(original*100)/100;
The specifics, in case the code isn't self-explanatory.
edit: ...or just use toFixed
, as proposed by Tim Büthe. Forgot that one, thanks (and an upvote) for reminder :)
kkyy
2009-03-19 09:39:50
In which case he should use Math.floor(). For positive numbers, that is...
xtofl
2009-03-19 09:44:31
Why would it give 0.35? 0.3445434 * 100 = 34.45434, Math.round(34.45434) = 34, 34 / 100 = 0.34...?
kkyy
2009-03-19 09:50:27
+2
A:
var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding
Ilya Birman
2009-03-19 09:40:54
+19
A:
There are functions to round numbers. For example:
var x = 5.0364342423;
print(x.toFixed(2));
will print 5.04.
Tim Büthe
2009-03-19 09:42:16
+11
A:
Be careful when using toFixed()
:
First, rounding the number is done using the binary representation of the number, which might lead to unexpected behaviour. For example
(0.595).toFixed(2) === '0.59'
instead of '0.6'
.
Second, there's an IE bug with toFixed()
. In IE (at least up to version 7, didn't check IE8), the following holds true:
(0.9).toFixed(0) === '0'
It might be a good idea to follow kkyy's suggestion or to use a custom toFixed()
function, eg
function toFixed(value, precision) {
var power = Math.pow(10, precision || 0);
return String(Math.round(value * power) / power);
}
Christoph
2009-03-19 10:56:07
Yes, this can be very important when creating code to predict prices. Thanks! +1
Fabio Milheiro
2010-10-07 15:39:14