JavaScript numbers to Words

2019-01-01 01:06发布

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

My Tactic goes like this:

  • Separate the digits to three and put them on Array (finlOutPut), from right to left.

  • Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

  • From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

<script type="text/javascript">
function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter  
        }
    }

        //convert The output Arry to , more printable string 
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19 
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}   
</script>

</head>
<body>

<input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/ 
    onkeydown="return (event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )"/>
                    <br/>
<div id="container">Here The Numbers Printed</div>
</body>
</html>

21条回答
裙下三千臣
2楼-- · 2019-01-01 01:45
<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>
查看更多
笑指拈花
3楼-- · 2019-01-01 01:47

There are JS library for en_US and cs_CZ.
You can use it standalone or as Node module.

查看更多
人气声优
4楼-- · 2019-01-01 01:47

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)

查看更多
登录 后发表回答