...

View Full Version : how to format a number with thousand seperators?



deadstone
10-15-2003, 05:38 PM
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

lavalamp
10-15-2003, 06:47 PM
I don't think this is a one liner, but I have got a considerably shorter version if you're interested:

joh6nn
10-15-2003, 07:27 PM
we had a challenge involving that a while back, actually. http://www.codingforums.com/showthread.php?s=&threadid=13577

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.

ggallen
10-17-2003, 05:34 PM
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);
decn=padit(decn,noplace);
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;
}

ggallen
10-17-2003, 05:35 PM
oops forgot these two

function padit(numb,nlen) {
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);
}
}

deadstone
10-17-2003, 06:04 PM
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

deadstone
10-21-2003, 09:53 AM
Hi all,

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

http://www.codingforums.com/showthread.php?s=&postid=142990#post142990



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

alert(formatNumber(1234567.89));
</script>



maybe that's all it takes!

cheers

Philip

rawsweets
03-26-2004, 06:50 AM
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!

ca_redwards
03-29-2004, 11:57 PM
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!

How about...



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!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum