Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!

num2word - JoeSimmons/tenfold

By: thetenfold on Jul 30th, 2013  |  syntax: JavaScript  |  size: 1.86 KB  |  views: 62  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. // num2word by JoeSimmons
  2. var num2word = (function () {
  3.     'use strict';
  4.     var  ones = {
  5.             '0' : 'zero', '1' : 'one', '2' : 'two', '3' : 'three',
  6.             '4' : 'four', '5' : 'five', '6' : 'six', '7' : 'seven',
  7.             '8' : 'eight', '9' : 'nine'
  8.         },
  9.         _10_19 = {
  10.             '10' : 'ten', '11' : 'eleven', '12' : 'twelve', '13' : 'thirteen',
  11.             '14' : 'fourteen', '15' : 'fifteen', '16' : 'sixteen',
  12.             '17' : 'seventeen', '18' : 'eighteen', '19' : 'nineteen'
  13.         },
  14.         tens = {
  15.             '2' : 'twenty', '3' : 'thirty', '4' : 'forty', '5' : 'fifty',
  16.             '6' : 'sixty', '7' : 'seventy', '8' : 'eighty', '9' : 'ninety'
  17.         };
  18.  
  19.     return function (num) {
  20.         var word = '', char0, nstr, rest;
  21.  
  22.         if ( isNaN( parseInt(num, 10) ) ) { return '(error - invalid argument)'; }
  23.  
  24.         nstr = (num + '').split('.')[0].replace(/^0+(\d+)/, '$1'); // format the number and make it a string
  25.         num = parseInt(nstr, 10); // get a number, even if it's a string
  26.         rest = nstr.substring(1); // cache the characters past the first to be used later
  27.         char0 = nstr.charAt(0); // make an array of characters
  28.  
  29.         if (num < 10) {               // 0 - 9
  30.             word = ones[char0];
  31.         } else if (num < 20) {        // 10 - 19
  32.             word = _10_19[nstr];
  33.         } else if (num < 100) {       // 20 - 99
  34.             word = tens[char0] + '-' + num2word(rest);
  35.         } else if (num < 1000) {      // 100 - 999
  36.             word = ones[char0] + ' hundred ' + num2word(rest);
  37.         } else if (num < 1000000) {   // 1,000 - 999,999
  38.             word = num2word( nstr.slice(0, -3) ) + ' thousand ' + num2word( nstr.slice(-3) );
  39.         } else {
  40.             return '(error - number too large)';
  41.         }
  42.  
  43.         return word.replace(/[ -]zero/g, '');
  44.     };
  45. }());