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

rounding to decimal places

Status
Not open for further replies.
Feb 16, 2003
87
GB
Hi,

I'm trying to round to decimal places - this code works on the whole but if that answer is 14.1 I want it to show as 14.10

Any ideas?

Simon

<script language="javascript"><!--

function doRound(x, places) {
return Math.round(x * Math.pow(10, places)) / Math.pow(10, places);
}

function updateGross() {
var taxRate = 17.5;
var grossValue = document.forms["FORM"].Amount.value;
var vat;

grossValue = grossValue * ((taxRate / 100) + 1);
vat = doRound(grossValue, 2) - document.forms["FORM"].Amount.value;

document.forms["FORM"].TOTAL.value = doRound(grossValue, 2);
document.forms["FORM"].VAT.value = doRound(vat, 2);
}

//--></script>
 
To maintain trailing zeroes, you'll have to convert the number to a string. I use the following to format amounts into dollars and cents:
Code:
function formatdollar(oneamount)
{
if (isNaN(oneamount)) return '&nbsp;';

if ((oneamount * 1) == 0) return '0.00';

var negative = '';

if ((oneamount * 1) < 0)
  {
  negative = '-';
  oneamount += '';
  oneamount = oneamount.substr(1);
  }

var newamount=Math.round(oneamount * 100) + '';
if (newamount < 10) newamount = '0' + newamount;
newamount = newamount.substr(0, newamount.length-2) + '.' + newamount.substr(newamount.length-2);
return (negative + newamount);
}

Lee
 
I KNEW there was something out there newer than my old function, but couldn't remember the method name. :)#

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top