Page 1 of 1
number formatting
Posted: Fri Apr 01, 2005 8:13 am
by gurjit
hi all,
why does this not work to format the number:
document.form1['tot_apply[]'][thenum].value = document.form1['theamountdue[]'][thenum].value. toFixed(2);
all i want to do is take the number calculated and display it like money (100.00) into the field tot_apply.
Posted: Sat Apr 02, 2005 11:19 am
by SystemWisdom
I wrote these long ago for an E-Comm site, they worked fine for me.. (alternative to 'toFixed')
Example:
Code: Select all
<html>
<head>
<script language="e;javascript"e;><!--
// This ensures users only type float numbers in textboxes
function isFloat( e )
{ var sValidNum = '0123456789.';
var chCode = (window.Event) ? e.which : e.keyCode;
if( (chCode == 13) || (chCode == 8) )
return true;
if( sValidNum.indexOf( String.fromCharCode( chCode ) ) == -1 )
return false;
}
// This formats a float into a string with specified decimal places..
function FixFloat( fNum, decPlaces )
{ var i, nDecimal = 1;
var tNum, nNum, sNum, aNum;
if( decPlaces == 0 ) return Math.round(fNum);
for( i = 0; i < decPlaces; i++ )
{ nDecimal *= 10;
}
tNum = Math.round(fNum * nDecimal);
tNum /= nDecimal;
nNum = Number(tNum);
sNum = nNum.toString();
if( sNum.indexOf("e;."e;) != -1 )
{ aNum = sNum.split("e;."e;);
if( aNumї1].length < decPlaces )
{ sNum = aNumї0] + "e;."e; + aNumї1];
for( i = 0; i < (decPlaces - aNumї1].length); i++ )
sNum += "e;0"e;;
}
}else
{ sNum += "e;."e;;
for( i = 0; i < decPlaces; i++ )
sNum += "e;0"e;;
}
return sNum;
}
// This is just for example:
function DoSubmit()
{ var frm = document.formsї0];
var myFloat = frm.txtBlah.value;
var myStrFloat = FixFloat( parseFloat(myFloat), 2 );
frm.txtDisplay.value = myStrFloat;
return;
}
//--></script>
</head>
<body>
<form name="e;frmBlah"e;>
Float-Only: <input type="e;text"e; name="e;txtBlah"e; value="e;"e; onkeypress="e;return isFloat(event);"e;>
<br><br>
<input type="e;text"e; name="e;txtDisplay"e; value="e;"e;>
<input type="e;button"e; value="e; Calc "e; onclick="e;DoSubmit()"e;>
</form>
</body>
</html>
Anyway, I hope that helps!