SitePoint Sponsor

User Tag List

Results 1 to 24 of 24

Hybrid View

  1. #1
    SitePoint Enthusiast Traduim's Avatar
    Join Date
    Feb 2003
    Location
    Catalonia
    Posts
    65
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Formatting numbers with Javascript

    I have this number:

    my_num = 123456789

    How could I get this: 123.456.789?
    Josep Tarrés,
    traducción
    traductor

  2. #2
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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;
    
    }
    Of course, that's just my opinion. I could be wrong.

  3. #3
    SitePoint Addict xDev's Avatar
    Join Date
    Jul 2003
    Location
    Moncton, New Brunswick, Canada
    Posts
    247
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Seems I got beaten to it, but since I been working on it (for you)
    for awhile ...

    Code:
    <html>
    <head>
    <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>
    </head>
    <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. #4
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.toString().group() ); // 100,000,000,.11,111
    
    alert( num.group() ); // 100,000,000.11111
    
    alert( num.group( "|", 4 ) ); // 1|0000|0000.11111
    Last edited by beetle; Sep 19, 2003 at 13:24.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  5. #5
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Beetle, your first example has a comma next to a decimal point....
    100,000,000,.11,111
    Surely that's wrong?!
    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  6. #6
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by M@rco
    Surely that's wrong?!
    I thought so too, but it is not so. Look closer.
    Of course, that's just my opinion. I could be wrong.

  7. #7
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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

    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  8. #8
    "Of" != "Have" bronze trophy Jeff Lange's Avatar
    Join Date
    Jan 2003
    Location
    Calgary, Canada
    Posts
    2,063
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I never doubted
    Who walks the stairs without a care
    It shoots so high in the sky.
    Bounce up and down just like a clown.
    Everyone knows its Slinky.

  9. #9
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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!

    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  10. #10
    SitePoint Addict xDev's Avatar
    Join Date
    Jul 2003
    Location
    Moncton, New Brunswick, Canada
    Posts
    247
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote 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>
    <head>
    <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>
    </head>
    <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. #11
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's more like it!

    Although... neither I nor he said that it was currency!
    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  12. #12
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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() ); // USD
    alert( sum.toCurrency( "\u00A3", "," ) ); // English pounds
    alert( sum.toCurrency( "F", ",", true ) ); // Francs
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  13. #13
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote 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)!!

    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  14. #14
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  15. #15
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.
    Of course, that's just my opinion. I could be wrong.

  16. #16
    "Of" != "Have" bronze trophy Jeff Lange's Avatar
    Join Date
    Jan 2003
    Location
    Calgary, Canada
    Posts
    2,063
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Canada doesn't use commas for number seperation, we use spaces.

    (Just in case anyone cares )
    Who walks the stairs without a care
    It shoots so high in the sky.
    Bounce up and down just like a clown.
    Everyone knows its Slinky.

  17. #17
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote 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!!!
    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  18. #18
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Spaces?

    Freaks.
    Of course, that's just my opinion. I could be wrong.

  19. #19
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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?
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  20. #20
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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.
    Of course, that's just my opinion. I could be wrong.

  21. #21
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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")
    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  22. #22
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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
    Then brother, I’m your man!


    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.

    Interesting link, thanks.
    Of course, that's just my opinion. I could be wrong.

  23. #23
    The doctor is in... silver trophy MarcusJT's Avatar
    Join Date
    Jan 2002
    Location
    London
    Posts
    3,509
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    DOH! Grand & tenner... guilty as charged!

    Cheers, Del!
    MarcusJT
    - former ASP web developer / former SPF "ASP Guru"
    - *very* old blog with some useful ASP code

    - Please think, Google, and search these forums before posting!

  24. #24
    SitePoint Enthusiast Traduim's Avatar
    Join Date
    Feb 2003
    Location
    Catalonia
    Posts
    65
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you very much for your help.
    It was certainly currency.
    Thanks to all.
    Josep Tarrés,
    traducción
    traductor


Bookmarks

Posting Permissions

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