Vaibhav Jain
Vaibhav Jain

Reputation: 34407

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.

Upvotes: 3

Views: 6374

Answers (3)

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>

Upvotes: 0

Carvellis
Carvellis

Reputation: 4042

How about

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

There are problems with toFixed. See this post.

Upvotes: 2

KooiInc
KooiInc

Reputation: 122898

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

Upvotes: 5

Related Questions