Created
August 25, 2018 16:54
-
-
Save saradornblaser/6610b744ab130b490ef1b6996da96be3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const numberToEnglish = n => { | |
| //handle exceptions; zero, >/< prescribed range, non-integers | |
| if (n === 0) | |
| return 'zero'; | |
| if (n < 0 || n > 99999) | |
| return ''; | |
| let strn = String(n).padStart(5,'0'); //convert to uniform, five digit string | |
| if (strn.includes('.')) | |
| return ''; | |
| //get strings for thousands, hundreds, and tens | |
| let thousands = strn.substring(0,2); | |
| if (thousands !== '00') | |
| var tString = twoDigit(thousands)+ ' thousand '; | |
| else | |
| var tString = ''; | |
| let hundreds = strn.substring(2,3); | |
| if (hundreds !== '0') | |
| var hString = oneDigit(hundreds) + ' hundred '; | |
| else | |
| var hString = ''; | |
| let tens = strn.substring(3); | |
| if (tens !== '00') | |
| var teString = twoDigit(tens); | |
| else | |
| var teString = ''; | |
| //join strings together and trim excess whitespace | |
| return (tString+hString+teString).trim(); | |
| } | |
| let singleDigits = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']; | |
| const oneDigit = a => { //a is a one char string | |
| return singleDigits[parseInt(a)]; | |
| } | |
| let doubleDigits = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']; | |
| const twoDigit = b => { //b is a 2 char string | |
| if (b[0] === '0') | |
| return oneDigit(b[1]); | |
| //handle special cases 10-19 | |
| else if (b[0] === '1') { | |
| if (b[1] === '0') | |
| return 'ten'; | |
| else if (b[1] === '1') | |
| return 'eleven'; | |
| else if (b[1] === '2') | |
| return 'twelve'; | |
| else if (b[1] === '3') | |
| return 'thirteen'; | |
| else if (b[1] === '5') | |
| return 'fifteen'; | |
| else if (b[1] === '8') | |
| return 'eighteen'; | |
| else | |
| return oneDigit(b[1])+'teen'; | |
| } | |
| else{ | |
| if (b[1] === '0') | |
| return doubleDigits[parseInt(b[0])]; | |
| else | |
| return doubleDigits[parseInt(b[0])] + ' ' + oneDigit(b[1]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment