1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| var numberToWords = function(num) { const map = ['Zero','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten', 'Eleven','Twelve',"Thirteen", "Fourteen", "Fifteen","Sixteen", "Seventeen", "Eighteen", "Nineteen"]; const multiplesOfTen = { 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety', 100: 'Hundred'}; const sanweishu = ['Hundred','Thousand','Million','Billion']; if(num === 0) return map[0]; let i = 0,ans = ''; while(num){ let temp = getSanWeishu(num); if(temp) ans = readSanWeishu(temp) + (i ? " " + sanweishu[i] + (ans ? " " : '') : '') + ans; num -= temp; num /= 1000; i++; } return ans; function readSanWeishu(num){ if(num < 20) { return map[num]; }else if(num >= 20 && num < 100){ if(num % 10 === 0) return multiplesOfTen[num]; else { let gewei = num % 10,shiwei = (num - gewei); return multiplesOfTen[shiwei] + ' ' + map[gewei]; } }else{ let baiwei = Math.floor(num / 100); let ans = map[baiwei] + ' ' + sanweishu[0]; if(num % 100 !== 0) ans += ' ' + readSanWeishu(num - baiwei * 100); return ans; } } function getSanWeishu(num){ let temp = 0,k = 3,jinzhi = 1; while(k && num){ let yushu = num % 10; temp += yushu * jinzhi; num -= yushu; num /= 10; jinzhi *= 10; k--; } return temp; } };
|