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
| var numberToWords = function(num) { if (!num) return 'Zero'; const numMap = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', 11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', 15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', 19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', 50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', 90: 'Ninety'}; const pointMap = {0: '', 1: 'Thousand', 2: 'Million', 3: 'Billion'};
const arr = []; let restNum = num; for(let i = 0; i <= 3; i++) { const mod = restNum % 1000; restNum = Math.floor(restNum / 1000); arr.unshift(mod); if (!restNum) break; } const readItem = (num) => { let str = []; const h = Math.floor(num / 100); mod = num % 100; if (h > 0) { str.push(numMap[h] + ' Hundred'); } if (mod) { if (mod <= 20) { str.push(numMap[mod]); } else { const p1 = mod - (mod % 10); str.push(numMap[p1]); if (mod % 10) { str.push(numMap[mod % 10]); } } } return str.join(' '); }
const readAll = (stack, idx, temp) => { if (!stack.length) { return temp.filter(i => i).join(' '); } let cur = readItem(stack.pop()); cur = cur ? cur + `${idx > 0 ? ' ' + pointMap[idx] : ''}` : ''; return readAll(stack, idx+1, [cur, ...temp]); }
return readAll(arr, 0, []); };
|