sashomaga

Convert numbers to number names, js, dictionary

Mar 2nd, 2013
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Write a script that converts a number in the range [0...999] to a text corresponding to its English pronunciation. Examples:
  2.     0 -> "Zero"
  3.     273 -> "Two hundred seventy three"
  4.     400 -> "Four hundred"
  5.     501 -> "Five hundred and one"
  6.     711 -> "Seven hundred and eleven"
  7.  
  8. function ConvertNumber() {
  9.     var cons = document.getElementById("console");
  10.     var numStr = document.getElementById("problem8").value;
  11.     var dict = {
  12.         0: "zero", 1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six",
  13.         7: "seven", 8: "eight", 9: "nine", 10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen", 15: "fifteen",
  14.         16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen", 20: "twenty", 30: "thirty", 40: "forty", 50: "fifty", 60: "sixty",
  15.         70: "seventy", 80: "eighty", 90: "ninety"
  16.     };
  17.     var result = "";
  18.     if (numStr.length == 3) {
  19.         result = dict[numStr[0]] + " hundred";
  20.         numStr = numStr.substring(1);
  21.         if (numStr == "00") {
  22.             cons.innerHTML = result;            
  23.             return;
  24.         }
  25.     }
  26.     if (!ExistInDictionary(numStr, dict, cons, result))
  27.     {
  28.         //common case  
  29.         if (result.length > 0) {
  30.             cons.innerHTML = result + " " + dict[(parseInt(numStr[0]) * 10).toString()] +" "+ dict[numStr[1]];
  31.         } else {
  32.             cons.innerHTML = dict[(parseInt(numStr[0]) * 10).toString()] + " " + dict[numStr[1]];
  33.         }
  34.     }
  35. }
  36. function ExistInDictionary(numStr,dict,cons,result)
  37. {
  38.     if (numStr in dict) {
  39.         if (result.length > 0) {
  40.             cons.innerHTML = result + " and " + dict[numStr];
  41.         } else {
  42.             cons.innerHTML = dict[numStr];
  43.         }        
  44.         return true;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment