Javascript number formating

AID: 8195
  • Status: Published

1420 points

  • Byivostoykov
  • TypeResource
  • Posted on2011-10-13 at 10:51:40
The task

A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome.

So let’s take a number like this “12345678.91¿ and format it to “12 345 678.91¿. To be shorter I assign it to a variable and hustled up following line which produced desired format:
> var n = "12345678.91";
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\.|,\./g, '.'));
> "12 345 678.91"
                                    
1:
2:
3:

Select allOpen in new window



How it’s made

First there is a string that has to be split somehow into triad. This is pretty simple – I’ve just used Regular expression with match and join methods to get the result back into a string using desired digital group separator (space in the case):
> n.match(/.{1,3}/g).join(' ');
> "123 456 78. 91"
                                    
1:
2:

Select allOpen in new window


The problem here is that RegExp is staring from left to right and produced wrong (from the task’s point of view) result. There is a two spaces where there shouldn’t be: after the dot and in the last triad (having two digits instead of three). First space I’ve eliminated adding regexp replace function.
> n.match(/.{1,3}/g).join(' ').replace(/\.\s/g, '.');
> "123 456 78.91"
                                    
1:
2:

Select allOpen in new window


Now it seems OK on the right of the dot. But last triad has still two digits. This is because RegExp rules passed to the match function are applied from left to right. So until dot is found it is impossible to predict how triad will be formed. Instead of applying more complicated regexp I’ve decided to reverse numbers before to add group separator.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ');
> "19. 876 543 21"
                                    
1:
2:

Select allOpen in new window


This way I’ve passed over the problem with the direction rules have been applied to the input. As the result is reversed at this point, I’ve to switch it back to original order adding same functions, this time on the right end.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('');
> "12 345 678 .91"
                                    
1:
2:

Select allOpen in new window


This is pretty close to desired result nevertheless there is one surplus delimiter before the dot. It might be easily eliminated using replace function.
> n.split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.');
> "12 345 678.91"
                                    
1:
2:

Select allOpen in new window


That’s it.


Some final thoughts:

  • What if we have a number instead of a string?
var n = 12345678.91;
                                    
1:

Select allOpen in new window


Applying the long line just composed against a number will produce an error…
Solution?

Just add one more step in front of all the others:
> n.toFixed(2).split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.');
> "12 345 678.91"
                                    
1:
2:

Select allOpen in new window



  • What if a number is required as result?

    Right! Still another step – multiplication by 1 – at the end.
> n.toFixed(2).split('').reverse().join('').match(/.{1,3}/g).join(' ').split('').reverse().join('').replace(/\s\./g, '.')*1;
> 12 345 678.91
                                    
1:
2:

Select allOpen in new window



Now you know how it's made ;-)
Asked On
2011-10-13 at 10:51:40ID8195
Tags

javascript

,

regexp

,

match

,

join

,

reverse

,

replace

,

split

Topic

JavaScript

Views
787

Comments

Expert Comment

by: myselfrandhawa on 2011-10-14 at 05:41:26ID: 32434

well how we show it then

Author Comment

by: ivostoykov on 2011-10-14 at 05:44:21ID: 32436

if you mean the result... Just assign it to a variable
// var res = n.toFixed(2).split('') ... put all the stuff here
                                        
1:

Select allOpen in new window

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top JavaScript Experts

  1. leakim971

    511,289

    Sage

    2,168 points yesterday

    Profile
    Rank: Genius
  2. mplungjan

    291,279

    Guru

    2,800 points yesterday

    Profile
    Rank: Savant
  3. nap0leon

    195,491

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  4. Proculopsis

    182,948

    Guru

    0 points yesterday

    Profile
    Rank: Sage
  5. COBOLdinosaur

    157,309

    Guru

    0 points yesterday

    Profile
    Rank: Genius
  6. chaituu

    130,684

    Master

    0 points yesterday

    Profile
    Rank: Sage
  7. Ray_Paseur

    130,217

    Master

    330 points yesterday

    Profile
    Rank: Savant
  8. tommyBoy

    125,345

    Master

    0 points yesterday

    Profile
    Rank: Genius
  9. StingRaY

    114,318

    Master

    0 points yesterday

    Profile
    Rank: Wizard
  10. DaveBaldwin

    80,081

    Master

    336 points yesterday

    Profile
    Rank: Genius
  11. ansudhindra

    79,054

    Master

    2,000 points yesterday

    Profile
    Rank: Wizard
  12. ChrisStanyon

    62,768

    Master

    800 points yesterday

    Profile
    Rank: Sage
  13. hielo

    61,266

    Master

    0 points yesterday

    Profile
    Rank: Savant
  14. HainKurt

    59,030

    Master

    0 points yesterday

    Profile
    Rank: Genius
  15. BuggyCoder

    54,739

    Master

    0 points yesterday

    Profile
    Rank: Sage
  16. mroonal

    54,339

    Master

    10 points yesterday

    Profile
    Rank: Sage
  17. tagit

    54,093

    Master

    1,600 points yesterday

    Profile
    Rank: Genius
  18. gurvinder372

    52,824

    Master

    10 points yesterday

    Profile
    Rank: Genius
  19. basicinstinct

    52,586

    Master

    0 points yesterday

    Profile
    Rank: Genius
  20. JonNorman

    45,158

    2,200 points yesterday

    Profile
    Rank: Master
  21. Lalit-Chandra

    44,420

    0 points yesterday

    Profile
    Rank: Master
  22. xmediaman

    36,450

    3,800 points yesterday

    Profile
    Rank: Guru
  23. kozaiwaniec

    33,100

    0 points yesterday

    Profile
    Rank: Guru
  24. Kravimir

    32,700

    0 points yesterday

    Profile
    Rank: Genius
  25. designatedinitializer

    32,300

    0 points yesterday

    Profile
    Rank: Master

Hall Of Fame