PDA

View Full Version : printing ending zero in dollars&cents


bcbasslet
10-11-2002, 09:28 PM
could someone help me print ending zeros in dollars and cents?
If my calculated figure is $1.50, it prints as 1.5
The ending zero vanishes.
I use Math.round(num*100)/100; to get my final calculated figure.
Do i have to parse thru the 1.50 to find the position of the decimal point, measure the remaining distance, and then concatenate a 0 if its 1, concate a .00 if the posit of the decimal is non existent?
I would be grateful for help in doing that. Thanks. Is it in the tutorials anywhere? I've read them all but don't remember.

beetle
10-11-2002, 09:38 PM
Here's a currency function..function currency(anynum)
{
//-- Returns passed number as string in $xxx,xxx.xx format.
anynum=eval(anynum)
workNum=Math.abs((Math.round(anynum*100)/100));workStr=""+workNum
if (workStr.indexOf(".")==-1){workStr+=".00"}
dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
pStr=workStr.substr(workStr.indexOf("."))
while (pStr.length<3){pStr+="0"}

//--- Adds comma in thousands place.
if (dNum>=1000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
}

//-- Adds comma in millions place.
if (dNum>=1000000) {
dLen=dStr.length
dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
}
retval = dStr + pStr
//-- Put numbers in parentheses if negative.
if (anynum<0) {retval="("+retval+")"}
return "$"+retval
}I didn't write this, but it works well enough. Example use...var num = 1.5;
var dollars = currency(num);
alert(dollars); // Alerts '$1.50'

bcbasslet
10-11-2002, 09:42 PM
you're brilliant! thanks so much.