Number to words for USD

    function numberToWords(num) {
        const units = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
        const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];
        const tens = ['Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];
        const thousands = ['Thousand', 'Million', 'Billion', 'Trillion'];


        function convert(num) {
            if (num < 10) return units[num];
            if (num < 20) return teens[num - 10];
            if (num < 100) return tens[Math.floor(num / 10) - 2] + (num % 10 ? ' ' + units[num % 10] : '');
            if (num < 1000) return units[Math.floor(num / 100)] + ' Hundred' + (num % 100 ? ' ' + convert(num % 100) : '');
            for (let i = 0; i < thousands.length; i++) {
                const unitValue = 1000 ** (i + 1);
                if (num < unitValue * 1000) {
                    return convert(Math.floor(num / unitValue)) + ' ' + thousands[i] + (num % unitValue ? ' ' + convert(num % unitValue) : '');
                }
            }
            return num.toString();
        }


        let dollars = Math.floor(num);
        let cents = Math.round((num - dollars) * 100);


        let dollarStr = dollars > 0 ? convert(dollars) + ' Dollar' + (dollars > 1 ? 's' : '') : '';
        let centStr = cents > 0 ? convert(cents) + ' Cent' + (cents > 1 ? 's' : '') : '';


        if (dollarStr && centStr) {
            return dollarStr + ' and ' + centStr;
        } else if (dollarStr) {
            return dollarStr;
        } else if (centStr) {
            return centStr;
        } else {
            return 'Zero Dollars';
        }
    }



Leave a comment

Your email address will not be published. Required fields are marked *