Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only two digits after decimal in javascript

I have a variable i=28.57142857142857; I want to alert(i); alert this variable on user screen. But I want only two digits after decimal. i.e 28.57

How to do it.

like image 374
Vaibhav Jain Avatar asked Dec 04 '25 17:12

Vaibhav Jain


1 Answers

try using toFixed:

 alert(i.toFixed(2));

If you need the precision mentioned in the next answer from Jappie, you could overwrite the native toFixed method like this:

Number.prototype.toFixed = function (precision) {
 var power = Math.pow(10, precision || 0);
 return String(Math.round(this * power) / power);
};
like image 130
KooiInc Avatar answered Dec 06 '25 07:12

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!