Skip to content

Instantly share code, notes, and snippets.

@unclebob
Created February 7, 2012 17:44
Show Gist options
  • Save unclebob/1760962 to your computer and use it in GitHub Desktop.
Save unclebob/1760962 to your computer and use it in GitHub Desktop.
A function to format a number with commas
(defn commatize [n]
(if (nil? n)
""
(let [s (str n)]
(apply str
(reverse (drop-last
(interleave
(reverse s)
(take (count s) (flatten (repeat [nil nil \,]))))))))))
@duarten
Copy link

duarten commented Feb 7, 2012

Or:

(defn commatize [n]
  (if (nil? n)
    ""
    (apply str (reverse (flatten (interpose \, (partition-all 3 (reverse (str n)))))))))

@nfma
Copy link

nfma commented Feb 7, 2012

I find this way a bit more readable:

(defn commatize [n]
  (if n 
    (->> n 
         str 
         reverse 
         (partition-all 3) 
         (interpose \,) 
         flatten 
         reverse 
         (apply str)) 
  ""))

@seancorfield
Copy link

Or just:

(defn commatize [n] (if n (-> (java.text.DecimalFormat.) (.format n)) ""))

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