Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 \,]))))))))))
@JonKernPA

This comment has been minimized.

Copy link

@JonKernPA JonKernPA commented Feb 7, 2012

it's so !obvious!

@duarten

This comment has been minimized.

Copy link

@duarten duarten commented Feb 7, 2012

Or:

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

This comment has been minimized.

Copy link

@nfma 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

This comment has been minimized.

Copy link

@seancorfield seancorfield commented Feb 8, 2012

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
You can’t perform that action at this time.