Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with code rounding to 2 decimal places

Status
Not open for further replies.

DH

Programmer
Dec 8, 2000
168
I have the following sample code to calculate a total.

It works great, but for example if you enter the number "9" in the text box and then tab out so the onblur will take effect, the total is displayed with many decimal places.

I do not work with html much and would like to know how I can I round this to always show 2 decimal places to the right?

<html>
<head>
</head>
<body>

<form name=&quot;form1&quot;>
Quantity <input type=&quot;text&quot;name=&quot;qty&quot;onblur=&quot;document.form1.total.value=document.form1.qty.value*99.95+4.95&quot;;/>
<input type=&quot;text&quot; name=&quot;total&quot;/> Total
</form>
</body>
</html>
 
<script>

function formatNum(expr,decplaces) {
var str = (Math.round(parseFloat(expr) * Math.pow(10,decplaces))).toString()
while (str.length <= decplaces) {
str = &quot;0&quot; + str
}
var decpoint = str.length - decplaces
return str.substring(0,decpoint) + &quot;.&quot; + str.substring(decpoint,str.length)
}


y= formatNum(23.55435,2);
Number to Round & number after decimal ie: 2 places, 4 places etc

alert(y);

This returns 23.55 DeZiner
gear.gif width=45 align=left
When the gears stop turning,
we all stop learning.
 
i have another solution:

var num=12.8756487
rez=Math.round(num*100)/100
alert(rez) Victor
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top