Convert digits into words with JavaScript

后端 未结 27 1491
我寻月下人不归
我寻月下人不归 2020-11-22 15:08

I am making a code which converts the given amount into words, heres is what I have got after googling. But I think its a little lengthy code to achieve a simple task. Two R

27条回答
  •  暖寄归人
    2020-11-22 15:40

    My solution is based on Juan Gaitán's solution for Indian currency, works up to crores.

    function valueInWords(value) {
        let ones = ['', 'one', 'two', 'three', 'four',
                'five', 'six', 'seven', 'eight', 'nine',
                'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
                'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];   
        let tens = ['twenty','thirty', 'forty','fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
        let digit = 0;   
        if (value < 20) return ones[value];   
        if (value < 100) {     
            digit = value % 10; //remainder     
            return tens[Math.floor(value/10)-2] + " " + (digit > 0 ? ones[digit] : "");   
        }
        if (value < 1000) {    
             return ones[Math.floor(value/100)] + " hundred " + (value % 100 > 0 ? valueInWords(value % 100) : "");   
        }   
        if (value < 100000) {     
            return valueInWords(Math.floor(value/1000)) + " thousand " + (value % 1000 > 0 ? valueInWords(value % 1000) : "");   
        }   
        if (value < 10000000) {     
            return valueInWords(Math.floor(value/100000)) + " lakh " + (value % 100000 > 0 ? valueInWords(value % 100000) : "");   
        }   
        return valueInWords(Math.floor(value/10000000)) + " crore " + (value % 10000000 > 0 ? valueInWords(value % 10000000) : ""); 
    }
    

提交回复
热议问题