Skip to content

Instantly share code, notes, and snippets.

@glucero
Created July 9, 2012 13:10
Show Gist options
  • Select an option

  • Save glucero/3076469 to your computer and use it in GitHub Desktop.

Select an option

Save glucero/3076469 to your computer and use it in GitHub Desktop.
Convert integers to english words.
; Convert numbers to english words.
(defn
single
[n]
(nth
'(one two three four five six seven eight nine)
(-
(Integer/parseInt
(str n))
1)
nil))
(defn
check-all
[n]
(or
(nth
'(ten eleven twelve fourteen)
(.indexOf
'(10 11 12 14)
(Integer/parseInt
(str n)))
nil)
(nth
'(twen thir for fif eigh)
(.indexOf
'(2 3 4 5 8)
(Integer/parseInt
(str n)))
nil)
(single n)))
(defn
int-power
[n]
(nth
(cons "thousand"
(for
[w
(map list
'(m b tr quadr quint sext sept oct non dec)
(iterate str "illion"))]
(apply str w)))
(- n 1)
nil))
(defn
organize-int
[n]
(for
[g (partition-all 3 (reverse n))]
(apply str
(reverse
(flatten
(cons g
(repeat
(- 3
(count g))
"0")))))))
(defn
convert
[n]
(if
(= \1
(first n))
(apply str
(check-all
(last n))
"teen")
(let
[s (single (last n))]
(str
(str
(check-all
(first n))
"ty")
(if-not
(nil? s)
(str "-" s))))))
(defn
tens
[n]
(if
(= \0
(first n))
(single
(Integer/parseInt
(str
(last n))))
(or
(check-all n)
(convert n))))
(defn
segment
[n]
(let
[s (last n)]
(let [r
(list
(when-not
(= \0
(first s))
(str
(single
(first s))
" hundred"))
(tens
(str
(second s)
(last s))))]
(when-not
(or
(empty?
(apply str r))
(> 0 (first n)))
(list r
(int-power
(first n)))))))
(defn
translate-int
[string]
(apply str
(interpose " "
(filter identity
(flatten
(list
(if
(=
(str string)
"0")
'(zero)
(reverse
(for [g
(map list
(iterate inc 0)
(organize-int
(str string)))]
(segment g))))))))))
(translate-int 1) ; => "one"
(translate-int 12) ; => "twelve"
(translate-int 123) ; => "one hundred twenty-three"
(translate-int 1234) ; => "one thousand two hundred thirty-four"
(translate-int 12345) ; => "twelve thousand three hundred forty-five"
(translate-int 123456) ; => "one hundred twenty-three thousand four hundred fifty-six"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment