2013-01-07 114 views
3
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Round to 2 Decimal Places</title> 
    <script type="text/javascript" 
    src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"> 
    </script> 
    <script type="text/javascript"> 
     $(function() { 
      $('input#txtNum').blur(function() { 
       var amt = parseFloat(this.value); 
       //$(this).val('$' + amt.toFixed(2)); 
       $(this).val((Math.round(amt*100))/100).toFixed(2); 
      }); 

     }); 
    </script> 
</head> 
<body> 
    Type a decimal number in the TextBox and hit Tab 
    <br /> 
    <input id="txtNum" type="text" /> 
</body> 
</html> 

,當我進入價值100.2569.The結果表明:100.26,但是當我進入56.999其表現出5-7,而不是57.00或者如果我不帶小數點的表現沒有小數無需兩臺給予價值在十進制後附加兩個零。的Javascript四捨五入至小數點後兩位

回答

6

你在錯誤的地方調用toFixed

$(this).val((Math.round(amt*100)/100).toFixed(2)); 
+0

由於其工作現在 – shiva

+0

這是使用jQuery做。這可以只使用Javascript來完成嗎? – shiva

+0

@shiva jQuery與香草JavaScript並不太相似。而不是'$(this).val()',你可以簡單地把結果賦給'this.value'。你需要什麼樣的瀏覽器支持?雖然更現代的瀏覽器支持'addEventListener',但當它存在時,您必須回退到'attachEvent',並且還可以返回到兩者都不存在時直接修改元素成員。 – Sampson

0

這可以使用Javascript如下進行:

this.value = (Math.round(amt*100)/100).toFixed(2); 

如果它是一個單一的文本輸入:

document.getElementById("txtNum").value = (Math.round(amt*100)/100).toFixed(2); 
+0

它看起來像代碼不按預期工作。有一個額外的')'產生一個SyntaxError。 '(amt * 100)/ 100'部分與'amt'相同。 – cbliard

+0

@cbliard:從問題中提取代碼「Math.round((amt * 100)/ 100).toFixed(2)」。因此,我不會檢查它的功能。 – TechSpellBound

+0

相當值得注意的是:原始代碼是(Math.round(amt * 100)/ 100).toFixed(2)' – cbliard

0

下面的示例代碼也適用。

ProperRoundCircle = function(num, decimal){ 
return Math.round(parseFloat(Number) * Math.pow(10, decimal))/Math.pow(10, decimal); 
} 
1

更簡單的比你想象:

amt.toFixed(2)