Click to See Complete Forum and Search --> : Javascript and rounding of numbers
Trine
05-24-2004, 10:18 AM
I know there is a lot of answers out there to rounding off numbers to 2 decimals in Javascript, but I can't use .toFixed() and Math.round((myVarNumber*100)/100) does not leave you with 2 decimals of you use a whole number (fx. 98). This is important as I am working with currency! I.e. there need to be 2 decimals at all times, even if it is .00
Please help.:confused: Is there a solution to this?
Please use simple language when explaining this to me as I am a Javascript beginner.
Thank you for your time.
requestcode
05-24-2004, 11:26 AM
Maybe this example will help:
<html>
<head>
<title>Rounding Numbers</title>
<SCRIPT LANGUAGE="JavaScript">
function calc(formid)
{
// convert the two values to numbers
numa=parseFloat(formid.txta.value)
numb=parseFloat(formid.txtb.value)
numc=numa+numb
formid.txtc.value=numc
// round to two decimal positions
var number=Math.round(numc * 100)/100
// convert back to string
var numd=number.toString()
nume=numd.split(".")
numelen=nume.length
if(numelen<2) // if whole number add decimal point and two zeros
{numd+=".00"}
else
{
if(nume[1].length<2) // if only one digit after decmal point add zero
{numd+="0"}
}
formid.txtd.value=numd
}
</SCRIPT>
</head>
<body>
<FORM NAME="myform">
First number <INPUT TYPE="text" NAME="txta" SIZE="10">
<br>
Second Number <INPUT TYPE="text" NAME="txtb" SIZE="10">
<br>
Before rounding<INPUT TYPE="text" NAME="txtc" SIZE="15">
<br>
After rounding <INPUT TYPE="text" NAME="txtd" SIZE="15">
<br>
<INPUT TYPE="button" NAME="but1" VALUE="Add" onClick="calc(this.form)">
</FORM>
</body>
</html>
toFixed (http://devedge.netscape.com/library/manuals/2000/javascript/1.5/reference/number.html#1200964)
var num=myVarNumber*100)/100;
alert(num.toFixed(2));