Created
February 7, 2012 17:44
-
-
Save unclebob/1760962 to your computer and use it in GitHub Desktop.
A function to format a number with commas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 \,])))))))))) |
Or:
(defn commatize [n]
(if (nil? n)
""
(apply str (reverse (flatten (interpose \, (partition-all 3 (reverse (str n)))))))))
I find this way a bit more readable:
(defn commatize [n]
(if n
(->> n
str
reverse
(partition-all 3)
(interpose \,)
flatten
reverse
(apply str))
""))
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
it's so !obvious!