JSFiddle - React, Tailwind, and code Playground

by Paco86

JavaScript

/**
 * @param {number} num
 * @return {string}
 */
var numberToWords = function(num) {
    if (num === 0) return 'Zero';
    
    var ones = ['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
    var tens = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
    var hundreds = 'Hundred';
    var thousands = ['Thousand', 'Million', 'Billion'];
    var level = 0;
    var res = [];
    
    var decimal = 	Math.floor(num * 100 % 100);
    
    if (decimal > 0) {
        res.push('and ' + decimal + ' / 100');
    }
    
    num = parseInt(num);
    while (num > 0) {
        var cur = num % 1000;
        var temp = [];
        if (cur >= 100) {
            var index = Math.floor(cur / 100) - 1;
            temp.push(ones[index] + ' ' + hundreds);
            cur %= 100;
        }
        
        if (cur >= 20) {
            var index = Math.floor(cur / 10) - 2;
            temp.push(tens[index]);
            cur %= 10;
        }
        
        if (cur > 0) {
            temp.push(ones[cur - 1]); 
        }
        
        if (temp.length > 0) {
            if (level > 0) {
                temp.push(thousands[level - 1]);
            }
            res.push(temp.join(' '))
        }
        
        level += 1;
        num = Math.floor(num / 1000);
        
    }
    
    return res.reverse().join(' ');
    
};

console.log(numberToWords(1223.42))