admin管理员组

文章数量:1356756

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.

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.

Share Improve this question asked Jun 4, 2010 at 8:57 Vaibhav JainVaibhav Jain 34.5k49 gold badges115 silver badges166 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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>

本文标签: netAllow only two digits after decimal in javascriptStack Overflow