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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parseFloat and two decimal places

Status
Not open for further replies.

Tarbuza

Technical User
Dec 13, 2000
56
0
0
US
I have the following code which works fine but it's giving me the result either without decimal places or if it is with a decimal place then it is showing up only character. For instance, 1250.5 instead of 1250.50.

Code is as follows. Any help would be greatly appreciated.

var f=document.forms[0];
f.Total.value=0;
f.Balance.value=0;
for(x=0;x<3;x++)
{
f.Total.value=parseFloat(f.TotalCharges(x).value,10)+parseFloat(f.Total.value);
f.Balance.value=parseFloat(f.BalanceDue(x).value,10)+parseFloat(f.Balance.value);
}
</script>
 
Well you must do it yourself. here is a function to produce the number of decimal places you want.

Code:
//usage
//var x = (roundDecimal(parseFloat(f.Total.value), 2))

function roundDecimal(nNumber, nDecimals) {
	var tenToPower;
	var newNumber;
	var numPad = 0;
	var curDecimal;
	var locDecimal;
	var i;

	// round the number
	tenToPower = Math.pow(10, nDecimals);
	newNumber = String((Math.round(nNumber * tenToPower) / tenToPower));
	
	if (nDecimals > 0) {
		// see if we need to pad with 0's
		locDecimal = newNumber.indexOf(&quot;.&quot;);
		if (locDecimal == -1) {
			// no decimal at all
			newNumber += &quot;.&quot;;
			numPad = nDecimals
		} else {
			// how much padding do we need?
			curDecimal = (newNumber.length - locDecimal) - 1;
			if (curDecimal < nDecimals) {
				numPad = nDecimals - curDecimal;
			}
		}

		// pad the end with 0's
		for (i = 0; i < numPad; i++) {
			newNumber += &quot;0&quot;;		
		}
	}

	return newNumber;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top