Last active
June 5, 2018 07:13
-
-
Save danivijay/a31859de2491bd56e1d69b5c0db5ab4a 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
function numberToWords (n) { | |
const num = ["zero", "one", "two", "three","four","five","six", "seven", "eight", "nine"] | |
const first = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "seventeen", "eighteen", "nineteen",] | |
const second = ["", "", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"] | |
let output = [] | |
const sNumber = n.toString() | |
const len = sNumber.length | |
let str = '' | |
for (var i = 0; i < len; i += 1) { | |
output.push(+sNumber.charAt(i)); | |
} | |
if (output[len - 1] !== undefined) { | |
// single digit | |
str += ' '+ num[output[len-1]] | |
} | |
if (output[len - 2] !== undefined) { | |
// two digit | |
if(output[len - 2] == 1) { | |
str = ' '+ first[output[len - 1]] | |
} else { | |
str += ' '+ second[output[len-2]] | |
} | |
} | |
if (output[len - 3] !== undefined) { | |
// three digit | |
str += ' and hundred' | |
str += ' '+ num[output[len-3]] | |
} | |
if (output[len - 4] !== undefined) { | |
// four digit | |
str += ' thousand' | |
str += ' '+ num[output[len-4]] | |
} | |
return str.split(" ").reverse().toString().replace(/,/g , " ") | |
} | |
console.log(numberToWords(9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment