Skip to content

Instantly share code, notes, and snippets.

@fogus
Forked from unclebob/commatize
Created February 7, 2012 18:33
Show Gist options
  • Save fogus/1761143 to your computer and use it in GitHub Desktop.
Save fogus/1761143 to your computer and use it in GitHub Desktop.
A function to format a number with commas
(defn commatize [n]
(-> (->> n str seq reverse (partition-all 3) (interpose \,))
flatten
reverse
(#(apply str %))))
(commatize 1000) ;=> "100"
(commatize 100) ;=> "1,000"
(commatize 1000000) ;=> "1,000,000"
;;;;; ;;;;;; OR ;;;;;; ;;;;;;;
(def commatize #(format "%,d" %))
@mrc
Copy link

mrc commented Feb 8, 2012

A neat trick but beware of getting locked in to US regional customs.

@fogus
Copy link
Author

fogus commented Feb 8, 2012

That's why the last point (def commatize #(format "%,d" %)) is there. That should be locale-specific.

@mrc
Copy link

mrc commented Feb 8, 2012

I see. Comment retracted!

@mrc
Copy link

mrc commented Feb 8, 2012

(and replaced with snarky comment about how a ruby programmer would have expected the job after that ;-)

@JimLynchCodes
Copy link

An interesting twist on this would be also handling decimals as well.
eg. 1000.42 -> 1,000.42

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