JavaScript numbers to Words

前端 未结 24 1216
死守一世寂寞
死守一世寂寞 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/

    0 讨论(0)
  • 2020-11-22 15:05

    I think this will help you

        aTens = [ "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy","Eighty", "Ninety"];
    
        aOnes = [ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" ];
        var aUnits = "Thousand";
        function convertnumbertostring(){
           var num=prompt('','enter the number');
           var j=6;
           if(num.length<j){
           var y = ConvertToWords(num);
           alert(y);
           }else{
              alert('Enter the number of 5 letters')
           }
        };
        function ConvertToHundreds(num)
        {
           var cNum, nNum;
           var cWords = "";
           if (num > 99) {
              /* Hundreds. */
              cNum = String(num);
              nNum = Number(cNum.charAt(0));
              cWords += aOnes[nNum] + " Hundred";
              num %= 100;
              if (num > 0){
                 cWords += " and "
              }
           }
    
           if (num > 19) {
              /* Tens. */
              cNum = String(num);
              nNum = Number(cNum.charAt(0));
              cWords += aTens[nNum - 2];
              num %= 10;
              if (num > 0){
                 cWords += "-";
              }
           }
           if (num > 0) {
              /* Ones and teens. */
              nNum = Math.floor(num);
              cWords += aOnes[nNum];
           }
           return(cWords);
    
        }
        function ConvertToWords(num)
        {
           var cWords;
           for (var i = 0; num > 0; i++) { 
               if (num % 1000 > 0) {
                  if (i != 0){
                     cWords = ConvertToHundreds(num) + " " + aUnits + " " + cWords;
                  }else{
                     cWords = ConvertToHundreds(num) + " ";
                  }        
               }
               num = (num / 1000);
           }
             return(cWords);
        }
    
    0 讨论(0)
  • 2020-11-22 15:08

    I tried Muhammad's solution, but had some issues and wanted to use decimals so I made some changes and converted to coffeescript and angular. Please bear in mind that js and coffeescript are not my strong suits, so use with care.

    $scope.convert = (number, upper=0) ->
    number = +number
    # console.log "inside convert and the number is:  " + number
    
    if number < 0
        # console.log 'Number Must be greater than zero = ' + number
        return ''
    
    if number > 100000000000000000000
        # console.log 'Number is out of range = ' + number
        return ''
    if isNaN(number)
        console.log("NOT A NUMBER")
        alert("Not a number = ")
        return ''
    else
        console.log "at line 88 number is:  " + number
        quintillion = Math.floor(number / 1000000000000000000)
        ### quintillion ###
    
        number -= quintillion * 1000000000000000000
        quar = Math.floor(number / 1000000000000000)
        # console.log "at line 94 number is:  " + number
    
        ### quadrillion ###
    
        number -= quar * 1000000000000000
        trin = Math.floor(number / 1000000000000)
        # console.log "at line 100 number is:  " + number
    
        ### trillion ###
        number -= trin * 1000000000000
        Gn = Math.floor(number / 1000000000)
        # console.log "at line 105 number is:  " + number
    
        ### billion ###
    
        number -= Gn * 1000000000
        million = Math.floor(number / 1000000)
        # console.log "at line 111 number is:  " + number
    
        ### million ###
    
        number -= million * 1000000
        Hn = Math.floor(number / 1000)
        # console.log "at line 117 number is:  " + number
    
        ### thousand ###
    
        number -= Hn * 1000
        Dn = Math.floor(number / 100)
        # console.log "at line 123 number is:  " + number
    
        ### Tens (deca) ###
    
        number = number % 100
        # console.log "at line 128 number is:  " + number
    
        ### Ones ###
        tn      = Math.floor(number / 10)
        one     = Math.floor(number % 10)
        # tn = Math.floor(number / 1)
        change  = Math.round((number % 1) * 100)
        res     = ''
        # console.log "before ifs"
        if quintillion > 0
            res += $scope.convert(quintillion) + ' Quintillion'
        if quar > 0
            res += $scope.convert(quar) + ' Quadrillion'
        if trin > 0
            res += $scope.convert(trin) + ' Trillion'
        if Gn > 0
            res += $scope.convert(Gn) + ' Billion'
        if million > 0
            res += (if res == '' then '' else ' ') + $scope.convert(million) + ' Million'
        if Hn > 0
            res += (if res == '' then '' else ' ') + $scope.convert(Hn) + ' Thousand'
        if Dn
            res += (if res == '' then '' else ' ') + $scope.convert(Dn) + ' Hundred'
        # console.log "the result is:  " + res
        ones = Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eightteen', 'Nineteen')
        tens = Array('', '', 'Twenty', 'Thirty', 'Fourty', 'Fifty', 'Sixty', 'Seventy', 'Eigthy', 'Ninety')
        # console.log "the result at 161 is:  " + res
        if tn > 0 or one > 0
            if !(res == '')
                # res += ' and '
                res += ' '
                # console.log "the result at 164 is:  " + res
            if tn < 2
                res += ones[tn * 10 + one]
                # console.log "the result at 168is:  " + res
            else
                res += tens[tn]
                if one > 0
                    res += '-' + ones[one]
                # console.log "the result at 173 is:  " + res
        if change > 0
            if res == ''
                res =  change + "/100"
            else
                res += ' and ' + change + "/100"
    
        if res == ''
            console.log 'Empty = ' + number
            res = ''
        if +upper == 1
            res = res.toUpperCase()
        $scope.newCheck.amountInWords = res
        return res
    

    $scope.is_numeric = (mixed_var) -> # console.log "mixed var is: " + mixed_var (typeof mixed_var == 'number' or typeof mixed_var == 'string') and mixed_var != '' and !isNaN(mixed_var)

    0 讨论(0)
  • 2020-11-22 15:08
    <script src="http://www.ittutorials.in/js/demo/numtoword.js" type="text/javascript"></script>
        HTML - Convert numbers to words using JavaScript</h1>
    <input id="Text1" type="text" onkeypress="return onlyNumbers(this.value);" onkeyup="NumToWord(this.value,'divDisplayWords');"
        maxlength="9" style="background-color: #efefef; border: 2px solid #CCCCC; font-size: large" />
    <br />
    <br />
    <div id="divDisplayWords" style="font-size: 13; color: Teal; font-family: Arial;">
    </div>
    
    0 讨论(0)
  • 2020-11-22 15:08

    If anybody ever wants to do this but in Spanish (en español), here's my code based on Hardik's

    function num2str(num, moneda) {
        moneda = moneda || (num !== 1 ? "pesos" : "peso");
        var fraction = Math.round(__cf_frac(num) * 100);
        var f_text = " (" + pad(fraction, 2) + "/100 M.N.)";
    
    
        return __cf_convert_number(num) + " " + moneda + f_text;
    }
    
    function __cf_frac(f) {
        return f % 1;
    }
    
    function __cf_convert_number(number) {
        if ((number < 0) || (number > 999999999)) {
            throw Error("N\u00famero fuera de rango");
        }
        var millon = Math.floor(number / 1000000);
        number -= millon * 1000000;
        var cientosDeMiles = Math.floor(number / 100000);
        number -= cientosDeMiles * 100000;
        var miles = Math.floor(number / 1000);
        number -= miles * 1000;
        var centenas = Math.floor(number / 100);
        number = number % 100;
        var tn = Math.floor(number / 10);
        var one = Math.floor(number % 10);
        var res = "";
    
        var cientos = Array("", "cien", "doscientos", "trescientos", "cuatrocientos", "quinientos", "seiscientos", "setecientos", "ochocientos", "novecientos");
        if (millon > 0) {
            res += (__cf_convert_number(millon) + (millon === 1 ? " mill\u00f3n" : " millones"));
        }
        if (cientosDeMiles > 0) {
            res += (((res == "") ? "" : " ") +
                cientos[cientosDeMiles] + (miles > 0 || centenas > 0 || tn > 0 || one < 0 ? (cientosDeMiles == 1 ? "to " : " ") : ""));
        }
        if (miles > 0) {
            res += (((res == "") ? "" : " ") +
                __cf_convert_number(miles) + " mil");
        }
        if (centenas) {
            res += (((res == "") ? "" : " ") +
                cientos[centenas] + (tn > 0 || one > 0 ? (centenas > 1 ? " " : "to ") : ""));
        }
    
    
        var ones = Array("", "un", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce", "quince", "dieciseis", "diecisiete", "dieciocho", "diecinueve");
        var tens = Array("", "", "veinte", "treinta", "cuarenta", "cincuenta", "sesenta", "setenta", "ochenta", "noventa");
    
        if (tn > 0 || one > 0) {
            if (tn < 2) {
                res += ones[tn * 10 + one];
            }
            else {
                if (tn === 2 && one > 0)
                    res += "veinti" + ones[one];
                else {
                    res += tens[tn];
                    if (one > 0) {
                        res += (" y " + ones[one]);
                    }
                }
            }
        }
    
        if (res == "") {
            res = "cero";
        }
        return res.replace("  ", " ");
    }
    
    function pad(num, largo, char) {
        char = char || '0';
        num = num + '';
        return num.length >= largo ? num : new Array(largo - num.length + 1).join(char) + num;
    }
    

    Result:

    num2str(123456789)
    "ciento veintitres millones cuatrocientos cincuenta y seis mil setecientos ochenta y nueve pesos (00/100 M.N.)"
    
    0 讨论(0)
  • 2020-11-22 15:09

    Source: http://javascript.about.com/library/bltoword.htm Smallest script that I found:

      <script type="text/javascript" src="toword.js">
        var words = toWords(12345);
        console.log(words);
      </script>
    

    Enjoy!

    0 讨论(0)
提交回复
热议问题