# Thread: Formatting numbers with Javascript

1. ## Formatting numbers with Javascript

I have this number:

my_num = 123456789

How could I get this: 123.456.789?

2. I wrote this code a while back, not knowing whether or not JavaScript had a built-in function for it:
Code:
```// ======================================
// Puts some nice comma's into a number
// to make it more readable,
//	eg,	1000 turns into 1,000
//		1000000.32 turns into 1,000,000.32
//		9999999.8888888 turns into 9,999,999.8888888
// and so on. Change sSep into the seperator/delimeter of
// your choice, otherwise "," is the default.
// ======================================

function number_Delimit ( n, sSep ) {

n = n.toString ( );
var p1, p2, p3;
var sSep = ( sSep == null ? ',' : sSep );

n = n.split ( '.' );
p1 = n [ 0 ];
p2 = ( n [ 1 ] == null ? '' : '.' + n [ 1 ] );
p3 = '';

for ( var i = p1.length-1 ; i >= 0; i -- ) {
p3 += p1.charAt ( p1.length - i - 1 );
if ( i % 3 == 0 && i != 0 ) p3 += sSep;
}

return p3 + p2;

}```

3. Seems I got beaten to it, but since I been working on it (for you)
for awhile ...

Code:
```<html>
<title>Format in Threes</title>
<script type="text/javascript">
function formatInThrees(n,d) // n = number, d = delimeter
{
var myNum = n.toString(),fmat = new Array();
for(var i = 1; i < myNum.length + 1; i++)
fmat[i] = myNum.charAt(i-1);

for(i = 1; i < myNum.length; i++)
{
if(i % 3 == 0) {
fmat[i] += d;
}
}
var val = fmat.join('');
return val;
}
</script>
<body bgcolor="#ffffff">
<form action="">
Enter a series of numbers:
<input type="text" name="jin" />
&nbsp; Result: <input type="text" name="jout" />
<input type="button" value="Click to Format"
onclick="this.form.jout.value =
formatInThrees(this.form.jin.value, '.')" />
</form>
</body>
</html>```
Example calls can be:

formatInThrees(123456789,'.')
// returns 123.456.789

formatInThrees(1234242341234234,',')
// returns 123,424,234,123,423,4

-xDev

4. My version [img]images/smilies/biggrin.gif[/img]
Code:
```String.prototype.group = function( chr, size )
{
if ( typeof chr == 'undefined' ) chr = ",";
if ( typeof size == 'undefined' ) size = 3;
return this.split( '' ).reverse().join( '' ).replace( new RegExp( "(.{" + size + "})(?!\$)", "g" ), "\$1" + chr ).split( '' ).reverse().join( '' );
}

Number.prototype.group = function( chr, size )
{
var num = this.toString().split( "." );
num[0] = num[0].group( chr, size );
return num.join( "." );
}

var num = 100000000.11111;

alert( num.group( "|", 4 ) ); // 1|0000|0000.11111```

5. Beetle, your first example has a comma next to a decimal point....
100,000,000,.11,111
Surely that's wrong?!

6. Originally Posted by M@rco
Surely that's wrong?!
I thought so too, but it is not so. Look closer.

7. That being wrong depends on what you consider right.

If right is returning the string with a comma every 3 characters, then it succeeds.

If right is returning the number with a comma every 3 numbers, but not in the decimal, then it fails.

The method is outputting exactly what it should - the inputted string with comma grouping every three characters. How you interface with it determines success.

Shame on you, M@rco, for doubting me

8. I never doubted

9. Traduim's original post is rather vague, and only appears to call for the digits to be grouped in threes, but given that this thread is in the javascript forum, and the thread is relating to formatting a number, it doesn't take much insight to realise that he wants to format the numbers for presentation to the user.

In case you didn't know, although we in the UK and US (and perhaps other countries) use a comma to delimit the thousands, millions, etc. and a decimal point to indicate where the fractional part of the number starts, in Europe (Traduim is from Catalonia, Spain) they use them the other way round.

Thus, the output of any such formatting must follow the conventions of the way that we write numbers, and thus outputs like "100,000,000,.11,111" (Beetle's) or "123,424,234,123,423,4" (xDev's) are not satisfactory - Beetle's allows a comma and a decimal point to appear together, and xDev's code groups the digits from left to right instead of right to left. Thus the code that each of you present *is* correct in the sense that it answers his original request, but fails to address the underlying need.

I shall leave you both to make the minor modifications to rectify your code!

10. Originally Posted by M@rco
Traduim's original post is rather vague, and only appears to call for the digits to be grouped in threes, but given that this thread is in the javascript forum, and the thread is relating to formatting a number, it doesn't take much insight to realise that he wants to format the numbers for presentation to the user.

In case you didn't know, although we in the UK and US (and perhaps other countries) use a comma to delimit the thousands, millions, etc. and a decimal point to indicate where the fractional part of the number starts, in Europe (Traduim is from Catalonia, Spain) they use them the other way round.

I shall leave you both to make the minor modifications to rectify your code!

M@rco,

Point well taken! I wasn't sure that he wanted currency formatting, so I just tried to do exactly what he said in the post. However, I can't pass up a chance to give the currency conversion a go:

Code:
```<html>
<title>Format Currency</title>
<script type="text/javascript">
function formatCurrency(n,d) // n = number, d = delimeter
{
// round to 2 decimals if cents present
n = (Math.round(n * 100) / 100).toString().split('.');
var
myNum = n[0].toString(),
fmat = new Array(),
len = myNum.length,
i = 1, deci = (d == '.') ? ',' : '.';
for(i; i < len + 1; i++) fmat[i] = myNum.charAt(i-1);

fmat = fmat.reverse();
for(i = 1; i < len; i++)
{
if(i % 3 == 0) {
fmat[i] += d;
}
}
var val = fmat.reverse().join('') +
( n[1] == null ? deci + '00' :
(deci + n[1])
);
return val;
}
</script>
<body style="font: 85% verdana, sans-serif;">
<form action="">
Enter a number (float or int):
<input type="text" name="jin" />
&nbsp;
Euros <input type="radio" name="t" checked="checked" />
Dollars <input type="radio" name="t" /><br />
Result: <input type="text" name="jout" />
<input type="button" value="Click to Format"
onclick="this.form.jout.value =
formatCurrency(this.form.jin.value,
(this.form.t[0].checked) ? '.' : ',')" />
</form>
</body>
</html>```
Example calls:

formatCurrency('100000000','.');
// 100.000.000,00

formatCurrency('100000000',',');
// 100,000,000.00

formatCurrency('1000.8756','.');
// 1.000,88

Cheers,
-xDev

11. That's more like it!

Although... neither I nor he said that it was currency!

12. M@rco - did you not notice that the Number version of group() properly groups only the non-decimal portion of the number? I did it this way on purpose.

No corrections needed, AFAIK.

For currency
Code:
```Number.prototype.round = function( places )
{
var rounder = Math.pow( 10, places );
return Math.round( this * rounder ) / rounder;
}

Number.prototype.toCurrency = function( unit, point, unitAfter )
{
if ( typeof unit == "undefined" ) unit = "\$";
if ( typeof point == "undefined" ) point = ".";
amt = this.round( 2 ).group( ( point == "." ) ? "," : "." ).replace( ".", point );
if ( /[.,]\d\$/.test( amt ) ) amt += "0";
return ( unitAfter ) ? amt + " " + unit : unit + " " + amt;
}

var sum = 123456.789;
alert( sum.toCurrency( "\u00A3", "," ) ); // English pounds
alert( sum.toCurrency( "F", ",", true ) ); // Francs```

13. Originally Posted by beetle
M@rco - did you not notice that the Number version of group() properly groups only the non-decimal portion of the number? I did it this way on purpose.

No corrections needed, AFAIK.
Ok, I see that works fine for the Number version, my mistake. The example with the string and the ,. threw me off the scent (although I still fail to see how that could ever be of any use to anyone)!!

14. True enough. But, for my style of coding, I prefer to keep things separate, and with methods like this, attached to the most approriate object. Adding non-numerical characters to a number is a string operation, so I put the bulk of the work there.

15. It’s very interesting reading all these different ways of performing essentially the same thing, and a learning experience for me too.

Just one thing beetle: Us limeys use the same way to delimit our currency as you yanks; £1,000.99.

16. Canada doesn't use commas for number seperation, we use spaces.

(Just in case anyone cares )

17. Originally Posted by Jeff Lange
Canada doesn't use commas for number seperation, we use spaces.

(Just in case anyone cares )
Of course we care! Even though you are freaks!!!

18. Spaces?

Freaks.

19. Thanks Mr. Brownstone. What about pence, shillings, crowns, etc, all that crap I hear in period movies -- it's all so confusing. Any of those still used?

20. The only one of those I know off the top of my head is that a Shilling is (was) worth 12 pence. 20 Shillings was equal to £1 (240 pennies,) but it is now 100 pennies to the pound.

It’s only pounds and pence (pennies) these days, although there are some colloquial variations to the naming of certain amounts. In London, a Monkey is £500, and a Quid is slang for a pound (in and out of London.) There are names for other amounts too, but you’ll need to ask a Cockney for those.

21. http://www.aldertons.com/money.htm

(although I have never needed to know any of that in my life.. the only slang that I or anyone else I know ever uses is "quid")

22. Oh, I’ve heard “pony” before:
Stick a pony in me pocket, I’ll fetch the suitcase from the van
Cause if you want the best, and you don’t ask questions

A grand; so frequently used most Brits don’t even think about it. Well, I didn’t. A tenner and a ton are the only other ones I know and get frequent use.

23. DOH! Grand & tenner... guilty as charged!

Cheers, Del!

24. Thank you very much for your help.
It was certainly currency.
Thanks to all.

#### Posting Permissions

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