Skip to content

Instantly share code, notes, and snippets.

@stukennedy
Created October 3, 2017 09:06
Show Gist options
  • Save stukennedy/784476cf5e5a670e665b5d5ad7c22f3e to your computer and use it in GitHub Desktop.
Save stukennedy/784476cf5e5a670e665b5d5ad7c22f3e to your computer and use it in GitHub Desktop.
Javascript code to convert numbers to words
/* demo on JSBIN https://jsbin.com/hunagoj/7/edit?js,console */
// jshint esnext: true
const mapIndex = _.map.convert({ cap: false })
const units = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
const tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
const thous = ['', 'thousand', 'million', 'billion', 'trillion']
const mapTens = ([u='0', t='']) =>
Number(t + u) < 20 ? units[Number(t + u)] : u === '0' ? tens[t] : `${tens[t]}-${units[u]}`
const mapSubBlocks = ([t, h='']) => [mapTens(t), !_.isEmpty(units[h]) ? `${units[h]} hundred` : '']
const mergeSubBlocks = ([t, h]) => _.isEmpty(t) ? h : (_.isEmpty(h) ? t : `${h} and ${t}`)
const mapBlock = (val, i) => _.isEmpty(val) ? '' : `${val} ${thous[i]}`
const convert = (number) =>
number
? _.flow(
String,
_.reverse,
_.chunk(3),
_.map(_.chunk(2)),
_.map(mapSubBlocks),
_.map(mergeSubBlocks),
mapIndex(mapBlock),
_.filter(val => !_.isEmpty(val)),
_.reverse,
_.join(', ')
)(number)
: 'zero'
console.log(convert(3789887))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment