Reputation: 59
<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>
when i am entering value as 100.2569.The result shows 100.26 but when i am entering 56.999 its showing 57 instead of 57.00 or if i am giving value without decimal its showing without decimals without two appending two zeroes after decimal.
Upvotes: 4
Views: 12062
Reputation: 1
The sample code below works, too.
ProperRoundCircle = function(num, decimal){
return Math.round(parseFloat(Number) * Math.pow(10, decimal)) / Math.pow(10, decimal);
}
Upvotes: 0
Reputation: 2555
This can be done using Javascript as follows:
this.value = (Math.round(amt*100)/100).toFixed(2);
If it is a single text input:
document.getElementById("txtNum").value = (Math.round(amt*100)/100).toFixed(2);
Upvotes: 2
Reputation: 268434
You're calling toFixed
in the wrong place:
$(this).val( (Math.round(amt*100)/100).toFixed(2) );
Upvotes: 6