Skip to content

Instantly share code, notes, and snippets.

@toolmantim
Created May 18, 2010 12:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save toolmantim/404927 to your computer and use it in GitHub Desktop.
Save toolmantim/404927 to your computer and use it in GitHub Desktop.
// A Javascript version of Allan Odgaard's thousands separator regex
// http://blog.macromates.com/2007/recursion-in-regular-expressions/
123456789.toString().replace(/(\d{1,3})(?=(\d{3})+(?!\d))/g, '$1,');
// => "123,456,789"
@ELLIOTTCABLE
Copy link

A WILD ONE-UP APPEARS:

number.to_s.split('.').tap { it[0] = it[0].reverse.scan(/\d{1,3}/).join(',').reverse }.join('.')

(It’s shorter without the radix-point float support: number.to_s.reverse.scan(/\d{1,3}/).join(',').reverse)

And now, homework: Make it automatically handle internationalization! :D

@toolmantim
Copy link
Author

only problem: it's the wrong language! ;)

@ELLIOTTCABLE
Copy link

Pfft, ‘wrong’ language. Ruby is delicious. Mind you, JavaScript and C are my main languages nowadays, but I still think my Ruby solution is pretty sexy ;D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment