Skip to content

Instantly share code, notes, and snippets.

@gkucmierz
Created October 28, 2016 17:27
Show Gist options
  • Select an option

  • Save gkucmierz/bc3163e061d514d6b8164bc9df78192f to your computer and use it in GitHub Desktop.

Select an option

Save gkucmierz/bc3163e061d514d6b8164bc9df78192f to your computer and use it in GitHub Desktop.
convert numbers to words up to 1e6 - 1
// convert numbers to words up to 1e6 - 1
function number2words(n) {
let ones = 'zero one two three four five six seven eight nine'.split(' ');
let tens = 'zero ten twenty thirty forty fifty sixty seventy eighty ninety'.split(' ');
let teens = 'thir four fif six seven eigh nine'.split(' ');
let w = (n) => {
if (n < 10) return ones[n];
if (n < 13) return 'ten eleven twelve'.split(' ')[n - 10];
if (n < 20) return teens[n - 13] + 'teen';
if (n < 100) return tens[n/10|0] + (n%10 === 0 ? '' : '-' + ones[n%10]);
if (n < 1000) return ones[n/100|0] + ' hundred' + (n%100 === 0 ? '' : ' ' + w(n%100));
return w(n*1e-3|0) + ' thousand' + (n%1e3 === 0 ? '' : ' ' + w(n%1e3));
};
return w(n);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment