views:

37

answers:

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.

A: 

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.

jkohlhepp
You don't need to write a whole method for a one-liner.
icio
A: 

Well, there's Number's toLocaleString:

Number(12345.67).toLocaleString();

It is locale specific however, so caveat emptor.

wombleton
+2  A: 

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
It is a regex, but it is also sexy.
wombleton