Delete digits after two decimal point not round number in javascript?
11,331
Solution 1
Use simple math instead;
document.write(Math.floor(i * 100) / 100);
You can stick it in your own function for reuse;
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
document.write(myToFixed(i, 2));
Solution 2
Just cut the longer string:
i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')
Related videos on Youtube
Comments
-
AMIN Gholibeigian almost 2 years
I have this :
i=4.568; document.write(i.toFixed(2));
output :
4.57
But i don't want to round the last number to 7 , what can i do?
-
AMIN Gholibeigian about 12 yearsThe function returns nothing ..!
-
AMIN Gholibeigian about 12 yearsshould be : document.write(Math.floor(i * 100)/ 100);
-
Angry 84 over 7 yearstoFixed is a shorter solution which does its job.
-
Steven.Chang over 2 yearsThis is not a correct method due to floating point number precision problem. Ex: try 0.29, you will get 0.28 instead