3

Say I have a string: 33400298.57

I've written a function (too long, too bloated, too substandard to post here) which formats this into:

33,400,298.57

The meat logic is the insertion of commas - leftwards of the decimal, every three places. Can there be a one line solution using regex to accomplish this? Presently, I'm splitting, reversing, looping to insert, reversing and joining again. Needless to say, it's unoptimal.

I'm looking for something like this:

Random color generator: '#'+Math.floor(Math.random()*16777215).toString(16);

Thanks.

JSTyro
  • 31
  • 1
  • check this link: http://software.dzhuvinov.com/jsworld.html – meo May 03 '10 at 10:52
  • Thanks, but really don't want to look up a library to find a line. That too a paid one. – JSTyro May 03 '10 at 10:56
  • Possible duplicate of [How can I format numbers as dollars currency string in JavaScript?](https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-dollars-currency-string-in-javascript) – avs099 Jul 27 '17 at 04:14

3 Answers3

2

How about this sexy little number with regex:

s = "33400298.57";
s.replace(/(?!^)(\d\d\d)(?=(\d\d\d)*\.)/g, ',$1'); // 33,400,298.57
icio
  • 3,060
  • 20
  • 22
0

Since I use jQuery on top of JavaScript, I would use a jQuery plugin. Something like this:

http://code.google.com/p/jquery-formatcurrency/

If you are using a different JavaScript library I would look for a plugin for that library instead. I would avoid writing your own formatting method. Don't reinvent the wheel.

RationalGeek
  • 9,425
  • 11
  • 62
  • 90
0

Well, there's Number's toLocaleString:

Number(12345.67).toLocaleString();

It is locale specific however, so caveat emptor.

wombleton
  • 8,336
  • 1
  • 28
  • 30