PDA

View Full Version : Help with function (adding commas, decimals, etc)


dep
02-15-2006, 08:47 PM
Hello. This function works, but it's horribly inefficient. I'm basically wanting to take a number, set it to two decimal places, add a dollar sign, (unless the noDollar flag is set to 1), and change the color based on negative values. I have the following function. It's ugly.. But it works. Could you possibly help me make this more efficient?

I documented the code below: Warning. It's ugly.


function deci(nStr, noDollar){
parseFloat(nStr)
nStr += '';

//Splitting before/after decimal
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;

while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}

//if x2 exists
if(x2){
//convert to integer
x2 = (parseFloat(x2));
//add decimal
x2 = x2.toFixed(2);
//since it's a decimal, it converts 0.99 to 1.00
//I have to account for this by....
if(x2 >= 1){
//Conver to string
x2 = x2.toString();
//Replace the X.00 part
x2 = x2.replace('1.', '.');
//Then, i have to fix what's on the LEFT side of the decimal.
//If x1 is a positive number, I have to add one.. else, subtract one.
if (x1 < 0){
x1 = parseFloat(x1) - 1;
}else{
x1 = parseFloat(x1) + 1;
}
}else{
//if x2 does not exist, i don't want there to be 0.00. Just x1 + 00...
//so this:
x2 = x2.toString();
x2 = x2.replace('0.', '.');
}
}

//If x2 doesn't exist at all, i want it to be .00
if (x2 == ''){
x2 = '.00';
}

//Combine them back again...
vars = x1 + x2;

//And now, if it's all less than 0, i change the color of it.
if (vars.replace(",", "") < 0){
vars = "<font color=red><b>-$"+vars.replace("-", "")+"</b></font>";
}else{
//if not, i simply add the dollarsign.
vars = "$"+vars;
}

//If the no dollar flag is on, remove the dollar sign.
if (noDollar == '1'){
vars = vars.replace('$', '');
}

return vars;
}