Advertisement
sirjordan

Spell Number

May 1st, 2014
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function spellNumber(num) {
  2.             var digitsContent = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"],
  3.                 teensContent = ["ten", "eleven", "twelve", "thirteen", "forteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"],
  4.                 tensContent = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"],
  5.                 num = num.toString(),
  6.                 result = new Array();
  7.  
  8.             // Three digit number
  9.             if (num.length > 2) {
  10.                 result.push(digitsContent[parseInt(num[0])]);
  11.                 result.push("hundred");
  12.  
  13.                 if (parseInt(num[1]) > 0) {
  14.                     // Get a substring of last 2 digits                  
  15.                     if (parseInt((num[1] + num[2])) <= 19) {
  16.                         result.push("and");
  17.                         result.push(teensContent[parseInt(num[2])]);
  18.                     } else {
  19.                         result.push(tensContent[parseInt(num[1]) - 2]);
  20.                         result.push(digitsContent[parseInt(num[2])]);
  21.                     }
  22.                 } else {
  23.                     result.push("and");
  24.                     result.push(digitsContent[parseInt(num[0])]);
  25.                 }
  26.  
  27.             } else {
  28.                 if (num.length > 1) {
  29.                     // That is 2 digits number
  30.                     if (parseInt((num[0] + num[1])) <= 19) {
  31.                         result.push(teensContent[parseInt(num[1])]);
  32.                     } else {
  33.                         result.push(tensContent[parseInt(num[0]) - 2]);
  34.                         result.push(digitsContent[parseInt(num[1])]);
  35.                     }
  36.                 } else {
  37.                     // That is just one digit
  38.                     result.push(digitsContent[parseInt(num[0])]);
  39.                 }
  40.             }
  41.  
  42.             // Make the first letter capital
  43.             result[0] = result[0].charAt(0).toUpperCase() + result[0].slice(1);
  44.             return result.join(' ');
  45.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement