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

Output to 2 Decimal Points 1

Status
Not open for further replies.

FAM

Technical User
Jan 13, 2003
345
GB
I have the following code which calculates an output based on a select box and outputs to html via
Code:
<b id='BaconBaguettesTotal'></b>
the problem is that it only outputs to 1 decimal place and i would like it output to 2 decimal places i.e. .00 , the function is given below
Code:
	function ddd(){	
		var d=document.getElementById("d")
		document.getElementById("BaconBaguettesTotal").innerHTML = d.options[d.selectedIndex].value * 1.80
	}
I have tried toFixed and toPrecision but to no avail due to lack of js experience.

Any suggestions?
Thanks
 
You might try this approach (just a hunch):

y = y.toDec(2);
 
toFixed(numdecimalplaces) should work fine
Code:
document.getElementById("BaconBaguettesTotal").innerHTML = (d.options[d.selectedIndex].value * 1.80).toFixed(2);

Lee
 
Pre 2.0 Safari doesn't recognize .toFixed() and quietly dies in response. Since toFixed() is the *perfect* solution for this problem you can use prototyping to insert manual formatting in those cases where toFixed() is not supported.

Code:
if ( !Number.prototype.toFixed ) {
  Number.prototype.toFixed = function( decimals ) {
// default to two decimal digits
    var decDigits = ( isNaN(decimals) ) ? 2 : decimals;
    var k         = Math.pow( 10, decDigits );
    var fixedNum  = Math.round( parseFloat(this) * k ) / k;
    var sFixedNum = new String( fixedNum );
    var aFixedNum = sFixedNum.split( "." );
    var i         = ( aFixedNum[1] ) ? aFixedNum[1].length : 0;
// append decimal point if needed
    if ( (i == 0) && (decDigits) ) { sFixedNum += "."; }
// append zeros if needed
    while ( i < decDigits ) {
      sFixedNum += "0";
      i++;
      }
    return sFixedNum;
  }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top