PDA

View Full Version : Dollar Math


kstarkey
09-30-2002, 05:26 PM
I want to calculate the difference between two numbers and return the value in dollars:

<SCRIPT LANGUAGE = "JavaScript">
<!--
// this function returns a dollar value
function dollars(n) {
var l = Math.floor(n);
var r = Math.round((100*n)%100);
if (r<10) return "$"+l+".0"+r;
if (r==100) return "$"+(l+1)+".00";
return "$"+l+"."+r;
}

I am using this script to format the difference as a dollar value.
Problem: it does not work if the difference is a negative number.
Does anyone have a suggestion to fix?
Thanks!
K

mordred
09-30-2002, 10:07 PM
I'm not quite sure if the minus symbol for negative values should be left of the dollar sign, but here you go:


function dollars(n) {
var sign = "";

if (n < 0) {
var n = Math.abs(n);
var sign = "-";
}

var l = Math.floor(n);
var r = Math.round((100*n)%100);

if (r < 10) {
return sign + "$"+l+".0"+r;
}
if (r == 100) {
return sign + "$"+(l+1)+".00";
}

return sign + "$"+l+"."+r;
}

kstarkey
09-30-2002, 10:17 PM
A BIG
Thank You!
It works perfectly!