PDA

View Full Version : add thousands separator


Alex Piotto
09-27-2002, 04:26 PM
Hi everybody!
I am using this code to round a number to two decimal after the dot

<SCRIPT>
function round(number,X) {
// rounds number to X decimal places, defaults to 2
X = (!X ? 2 : X);
return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}
</SCRIPT>

So, for example, a number like this 123456789.65786578657
will be 123456789.66

Now, I need to put inside this script also a function to add the commas in the thousands places, without losing the rounded decimals.

I tryed several scripts around, but, or I lose the decimals or a comma is added in front of the dot... :(

finally, I need my number to be 123,456,789.66 !

Any help?

Thanks

Alex

adios
09-27-2002, 04:33 PM
Courtesy Karen Gayda:

function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.

PARAMETERS:
strValue - source string containing commas.

RETURNS: String modified with comma grouping if
source was all numeric, otherwise source is
returned.

REMARKS: Used with integers or numbers with
2 or less decimal places.
*************************************************/
var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

//check for match to search criteria
while(objRegExp.test(strValue)) {
//replace original string with first group match,
//a comma, then second group match
strValue = strValue.replace(objRegExp, '$1,$2');
}
return strValue;
}

x = 123456789.65786578657;
x = round(x)
alert(x);
alert(addCommas(x.toString()));

http://www.rgagnon.com/jsdetails/js-0063.html

Alex Piotto
09-27-2002, 04:48 PM
Thanks adios
I'll try it right now!
Alex