Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @param {number} num
- * @return {string}
- */
- const thousand = 1000;
- const million = thousand * thousand;
- const billion = million * thousand;
- const trillion = billion * thousand;
- const quadrillion = trillion * thousand
- const quintillion = quadrillion * thousand;
- const units = [undefined, "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
- const teens = ["Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
- const tens = [undefined, "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"]
- function subHundred(num){
- const trimmed = num % 100
- const unit = trimmed % 10;
- const ten = Math.floor(trimmed / 10);
- if(ten >= 2){
- return [tens[ten], units[unit]]
- .filter(part => part)
- .join(' ');
- }
- if(ten >= 1){
- return teens[unit];
- }
- return units[unit];
- }
- function subThousand(num){
- const trimmed = num % 1000;
- const parts = [trimmed >= 100 && `${units[Math.floor(trimmed / 100)]} Hundred`, subHundred(trimmed)];
- return parts.filter(part => part).join(' ') || undefined;
- }
- function getThousandPower(min, word) {
- return function(num){
- const numOfMins = subThousand(Math.floor((num % (min * thousand)) / min ));
- return numOfMins && `${numOfMins} ${word}`;
- }
- }
- var numberToWords = function(num) {
- return [
- getThousandPower(quadrillion, "Quadrillion"),
- getThousandPower(trillion, "Trillion"),
- getThousandPower(billion, "Billion"),
- getThousandPower(million, "Million"),
- getThousandPower(thousand, "Thousand"),
- subThousand
- ].map(proc => proc(num))
- .filter(part => part)
- .join(" ") || "Zero";
- };
- [000, 12345, 1234567, 1234567891].forEach(num => {
- console.log(numberToWords(num));
- });
Add Comment
Please, Sign In to add comment