Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: how to format a number with thousand seperators?

1. ## how to format a number with thousand seperators?

Hi all,

Is it possible using a regular expression / pattern matching/replacemenet (or the Math object ?) to format a number like this:

Format this :
-22313256

to this:

-22,313,256.00

Now, we came up with this:
>>> Function >>>>>

function formatthousands (number, precision){
var finalstring, tnumber, buffer;
var flag;
if(number<0) {
flag="-";
number=Math.abs(number) ;
}else
{
flag="";
}
finalstring=new String();
var decimal = number%1;
var integer = number-decimal;
decimal=number-integer;
while (integer > 0){
tnumber = integer/1000;
buffer=Math.round(1000*(tnumber-Math.floor(tnumber)))
finalstring=buffer.toString()+","+finalstring;
// WScript.Echo(finalstring);
integer=tnumber-(tnumber%1);
}
finalstring=finalstring.substring(0,finalstring.length-1);

if (precision!=0)
{
if (decimal==0)
{
decimal = "0.0000000000000000001"
}
finalstring=finalstring+"."+decimal.toString().substr(2).substr(0,precision);
}
return (flag+finalstring);
};

//WScript.Echo(formatthousands (-124656.001,0))

<<<<< END <<<<

but can it be done with a one-line regular expression?

If so, can u help me please?

thanks

Philip

• I don't think this is a one liner, but I have got a considerably shorter version if you're interested:

• we had a challenge involving that a while back, actually. New Code Challenge!

if i weren't a lazy jerk, i would actually combine aspects of all the solutions that were presented in the challenge, but i AM a lazy jerk, and as such, i only just corrected the bugs i found in my code.

i haven't looked at lavalamp's code, but i would suggest looking at everyone's code, and then deciding what works best for you. or, if you're motivated enough, you might even do what i should have, and try to combine the best elements of everyone's solution.

• Below are the functions I use

function removecomma(numb) {
var temporary="";
for (var i=0;i < numb.length;++i) {
var c=numb.charAt(i);
if (c!=",") {temporary += c;}
}
return temporary;
}

function putcomma(numb,noplace) {
var temporary = "";
var cplace = 0 ;
var decn=numb-makeint(numb);
decn=decn * (Math.pow(10,noplace));
decn=Math.round(decn);
decn=Math.abs(decn);
var wholen=makeint(numb)+"";
var ii=wholen.length-1;
for (var i=ii;i > -1;i=i-1) {
var c=wholen.charAt(i)+"";
if (c != "-") {
if (cplace == 3) {
temporary = "," + temporary + "" ;
cplace = 0 ;
}
temporary = c + temporary + "" ;
cplace = cplace + 1 ;
} else {
temporary = c + temporary + "" ;
}
}
temporary = temporary + "." + decn + "";
return temporary;
}

• oops forgot these two

var str="" + numb ;
while (str.length < nlen) {
str=str+"0";
}
return str;
}

function makeint(numb) {
if (numb < 0) {
return Math.ceil(numb);
} else {
return Math.floor(numb);
}
}

• ## thanks everyone

for these excellent suggestions...

We also found out that we can call a VB function from JavaScript and do it in a kind of roundabout way with only one or 2 lines of code!

cheers

Philip

• ## The best yet!

Hi all,

this guy LeRexus posted this in answer to another desparate post of mine:

http://www.codingforums.com/showthre...990#post142990

<script>
function formatNumber(num,spl){
return num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/img,'\$1,').split('').reverse().join('');
}

</script>
maybe that's all it takes!

cheers

Philip

• ## bug and fix for regexp solution

Thanks for posting here deadstone. Your regexp turned out to be a jump start on a quick fix. I found one error with the regexp and added a feature, many may find useful.

My js needed to list monetary values, in which case the decimal portion required padding if (present). My addition doesn't *add* a decimal portion if it wasn't there, but it does add a 0 (zero) if a single-digit decimal exists.

I added the following to the end of the statement:

.replace(/\d(\.\d)\b/mg,'\$1Z').replace(/(Z)\b/mg,'0')

This is not the best line in the world, but it's the only way I could add a number after using a back-reference. I add a capital "Z" and then replace that with a zero. It's ugly but it works, and know that any trailing "Z"s may be replaced with a zero.

Then I noticed a bug in the original statement... if the number already has a single-digit decimal the commas are placed incorrectly. So, I placed the above code, *before* the comma-inserting-code... sorta like a fixed to numbers with single-digit decimals.

Nevertheless, below is the entire statement which pads a zero and inserts commas into numeric values.

num = num.toString().replace(/\d(\.\d)\$/mg,'\$1Z').replace(/(Z)\$/mg,'0').split('').reverse().join('').replace(/(?=\d\.?)(\d{3})(?=\d)/mg,'\$1,\$2').split('').reverse().join('').replace(/\d(\.\d)\$/mg,'\$1Z').replace(/(Z)\$/mg,'0');

Enjoy, and if anyone has a way of getting around the double-replacement style of padding numerics, please post!

- Best O'Luck!

• ## getting around the double-replacement

Originally Posted by rawsweets
Thanks for posting here deadstone. Your regexp turned out to be a jump start on a quick fix. I found one error with the regexp and added a feature, many may find useful.

My js needed to list monetary values, in which case the decimal portion required padding if (present). My addition doesn't *add* a decimal portion if it wasn't there, but it does add a 0 (zero) if a single-digit decimal exists.

I added the following to the end of the statement:

.replace(/\d(\.\d)\b/mg,'\$1Z').replace(/(Z)\b/mg,'0')

This is not the best line in the world, but it's the only way I could add a number after using a back-reference. I add a capital "Z" and then replace that with a zero. It's ugly but it works, and know that any trailing "Z"s may be replaced with a zero.

Then I noticed a bug in the original statement... if the number already has a single-digit decimal the commas are placed incorrectly. So, I placed the above code, *before* the comma-inserting-code... sorta like a fixed to numbers with single-digit decimals.

Nevertheless, below is the entire statement which pads a zero and inserts commas into numeric values.

num = num.toString().replace(/\d(\.\d)\$/mg,'\$1Z').replace(/(Z)\$/mg,'0').split('').reverse().join('').replace(/(?=\d\.?)(\d{3})(?=\d)/mg,'\$1,\$2').split('').reverse().join('').replace(/\d(\.\d)\$/mg,'\$1Z').replace(/(Z)\$/mg,'0');

Enjoy, and if anyone has a way of getting around the double-replacement style of padding numerics, please post!

- Best O'Luck!

Code:
```function punctuated(n){
var s=(''+n).split('.');
s[0]=s[0].split('').reverse().join('').match(/\d{1,3}/gi).join(',').split('').reverse().join('');
return(s.join('.'));
}```
First, this splits the number (forced to be a string) around the decimal point (if any). Second, it reverses the integer portion (split/reverse/join), matches up to three digits (regular expression's standard greedy algorithm), joins these trios with commas, and unreverses the punctuated integer (split/reverse/join). Finally, it returns the whole puncuated number including original decimal portion.

Enjoy!

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•