JavaScript numbers to Words

前端 未结 24 1584
死守一世寂寞
死守一世寂寞 2020-11-22 14:39

I\'m trying to convert numbers into english words, for example 1234 would become: \"one thousand two hundred thirty four\".

My Tact

24条回答
  •  一向
    一向 (楼主)
    2020-11-22 15:04

    Here, I wrote an alternative solution:

    1) The object containing the string constants:

    var NUMBER2TEXT = {
        ones: ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'],
        tens: ['', '', 'twenty', 'thirty', 'fourty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'],
        sep: ['', ' thousand ', ' million ', ' billion ', ' trillion ', ' quadrillion ', ' quintillion ', ' sextillion ']
    };
    

    2) The actual code:

    (function( ones, tens, sep ) {
    
        var input = document.getElementById( 'input' ),
            output = document.getElementById( 'output' );
    
        input.onkeyup = function() {
            var val = this.value,
                arr = [],
                str = '',
                i = 0;
    
            if ( val.length === 0 ) {
                output.textContent = 'Please type a number into the text-box.';
                return;  
            }
    
            val = parseInt( val, 10 );
            if ( isNaN( val ) ) {
                output.textContent = 'Invalid input.';
                return;   
            }
    
            while ( val ) {
                arr.push( val % 1000 );
                val = parseInt( val / 1000, 10 );   
            }
    
            while ( arr.length ) {
                str = (function( a ) {
                    var x = Math.floor( a / 100 ),
                        y = Math.floor( a / 10 ) % 10,
                        z = a % 10;
    
                    return ( x > 0 ? ones[x] + ' hundred ' : '' ) +
                           ( y >= 2 ? tens[y] + ' ' + ones[z] : ones[10*y + z] );
                })( arr.shift() ) + sep[i++] + str;
            }
    
            output.textContent = str;
        };
    
    })( NUMBER2TEXT.ones, NUMBER2TEXT.tens, NUMBER2TEXT.sep );
    

    Live demo: http://jsfiddle.net/j5kdG/

提交回复
热议问题