简体   繁体   中英

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. ie 28.57

How to do it.

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);
};

How about

alert(Math.round(i * 100) / 100);

There are problems with toFixed. See this post .

100% working!!!!

 <html> <head> <script> function replacePonto(){ var input = document.getElementById('qtd'); var ponto = input.value.split('.').length; var slash = input.value.split('-').length; if (ponto > 2) input.value=input.value.substr(0,(input.value.length)-1); if(slash > 2) input.value=input.value.substr(0,(input.value.length)-1); input.value=input.value.replace(/[^0-9.-]/,''); if (ponto ==2) input.value=input.value.substr(0,(input.value.indexOf('.')+3)); if(input.value == '.') input.value = ""; } </script> </head> <body> <input type="text" id="qtd" maxlength="10" style="width:140px" onkeyup="return replacePonto()"> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM