Convert digits into words with JavaScript

后端 未结 27 1245
我寻月下人不归
我寻月下人不归 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:53

    I modified @McShaman's code, converted it to CoffeeScript, and added docs via JSNice. Here's the result, for those interested (English):

    ###
        Convert an integer to an English string equivalent
        @param {Integer} number the integer to be converted
        @return {String} the English number equivalent
    ###
    inWords = (number) ->
        ###
            @property {Array}
        ###
        englishIntegers = [
            ""
            "one "
            "two "
            "three "
            "four "
            "five "
            "six "
            "seven "
            "eight "
            "nine "
            "ten "
            "eleven "
            "twelve "
            "thirteen "
            "fourteen "
            "fifteen "
            "sixteen "
            "seventeen "
            "eighteen "
            "nineteen "
        ]
    
        ###
            @property {Array}
        ###
        englishIntegerTens = [
            ""
            ""
            "twenty"
            "thirty"
            "forty"
            "fifty"
            "sixty"
            "seventy"
            "eighty"
            "ninety"
        ]
    
        ###
            @property {Array}
        ###
        englishIntegerThousands = [
            "thousand"
            "million"
            ""
        ]
        number = number.toString()
        return "" if number.length > 9
    
        ###
            @property {string}
        ###
        number = ("000000000" + number).substr(-9)
    
        ###
          @property {(Array.<string>|null)}
          ###
        number = number.match(/.{3}/g)
    
        ###
            @property {string}
        ###
        convertedWords = ""
    
        ###
            @property {number}
        ###
        i = 0
        while i < englishIntegerThousands.length
    
            ###
                @property {string}
            ###
            currentNumber = number[i]
    
            ###
                @property {string}
            ###
            tempResult = ""
            tempResult += (if convertedWords isnt "" then " " + englishIntegerThousands[i] + " " else "")
            tempResult += (if currentNumber[0] isnt 0 then englishIntegers[Number(currentNumber[0])] + "hundred " else "")
    
            ###
                @property {string}
            ###
            currentNumber = currentNumber.substr(1)
            tempResult += (if currentNumber isnt 0 then ((if tempResult isnt "" then "and " else "")) + (englishIntegers[Number(currentNumber)] or englishIntegerTens[currentNumber[0]] + " " + englishIntegers[currentNumber[1]]) else "")
            convertedWords += tempResult
            i++
        convertedWords
    
    0 讨论(0)
  • 2020-11-22 15:53

    Convert digits to word in French language using JavaScript and html - original French words

        <html>
            <head>
                <title>Number to word</title>
    
                <script>
                    function toWords() {
                        var s = document.getElementById('value').value;
                        var th = ['','mille','million', 'milliard','billion'];
                        var dg = ['zéro','un','deux','trois','quatre', 'cinq','six','sept','huit','neuf'];
                        var tn = 
    
    ['dix','onze','douze','treize', 'quatorze','quinze','seize', 'dix-sept','dix-huit','dix-neuf'];
                    var tw = ['vingt','trente','quarante','cinquante', 'soixante','soixante-dix','quatre-vingt','quatre-vingt-dix'];
                    s = s.toString();
                    s = s.replace(/[\, ]/g,'');
                    if (s != parseFloat(s)) return 'not a number';
                    var x = s.indexOf('.');
                    if (x == -1)
                        x = s.length;
                    if (x > 15)
                        return 'too big';
                    var n = s.split(''); 
                    var str = '';
                    var sk = 0;
                    for (var i=0;   i < x;  i++) {
                        if ((x-i)%3==2) { 
                            if (n[i] == '1') {
    
                                str += tn[Number(n[i+1])] + ' ';
                                i++;
                                sk=1;
                            } else if (n[i]!=0) { 
                                if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                                if(s==20 || s==30 || s==40 || s==50 || s==60 || s==70 || s==80 || s==90){
                                str += tw[n[i]-2] + ' ';} // for not to display hyphens for 20,30...90 
                                else{
                                str += tw[n[i]-2] + '-';}
                                sk=1;
                                }
                            }
                        } else if (n[i]!=0) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
    
                            str += dg[n[i]] +' ';
                            if ((x-i)%3==0) str += 'hundert ';  // for start from 101 - 
    
                            sk=1;
                            }
                        }
                        if ((x-i)%3==1) {
                            if(s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                            if (sk)
                                str += th[(x-i-1)/3] + ' ';
                            sk=0;
                            }
                        }
                    }
    
                    if (x != s.length) {
                        var y = s.length;
                        //str += 'point ';
                        //for (var i=x+1; i<y; i++)
                        //  str += dg[n[i]] +' ';
                        str += 'virgule ';
                         var counter=0;
                         for (var i=x+1; i<y; i++){
                            if ((y-i)%3==2) { 
                                                if (n[i] == '1') {
                                                                str += tn[Number(n[i+1])] + ' ';
                                                                i++;
                                                                counter=1;
                                                } else if (n[i]!=0) {
                                                                str += tw[n[i]-2] + '-';
                                                                counter=1;
                                                }
                                            }else if (n[i]!=0) { // 0235
                                                str += dg[n[i]] +' ';
                                            }
                         }
    
                    }
    
                    if (s!=21 && s!=31 && s!=41 && s!=51 && s!=61 && s!=71 && s!=72 && s!=73 && s!=74 && s!=75 && s!=76 && s!=100 && s!=91 && s!=92 && s!=93 && s!=94 && s!=95 && s!=96){
                    document.getElementById("demo").innerHTML = str.replace(/\s+/g,' ')
    
                    }
                    else if (s==21){
                    str = 'vingt-et-un'
                    document.getElementById("demo").innerHTML = str;
                    }//alert(str.replace(/\s+/g,' '));
                    else if (s==31){
                    str = 'trente-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==41){
                    str = 'quarante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==51){
                    str = 'cinquante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==61){
                    str = 'soixante-et-un'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==71){
                    str = 'soixante-et-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==72){
                    str = 'soixante-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==73){
                    str = 'soixante-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==74){
                    str = 'soixante-quatorze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==75){
                    str = 'soixante-quinze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==76){
                    str = 'soixante-seize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==100){
                    str = 'cent'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==91){
                    str = 'quatre-vingt-onze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==92){
                    str = 'quatre-vingt-douze'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==93){
                    str = 'quatre-vingt-treize'
                    document.getElementById("demo").innerHTML = str;}
                    else if (s==94){
                    str = 'quatre-vingt-quatorze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==95){
                    str = 'quatre-vingt-quinze'
                    document.getElementById("demo").innerHTML = str;}   
                    else if (s==96){
                    str = 'quatre-vingt-seize'
                    document.getElementById("demo").innerHTML = str;}               
                }
            </script>
        </head>
        <body>
            <p>Enter only numbers (max 15 digits) : </p>
            <input type="text" name="value" id='value' /><br>
            <input type="button" value="submit" onclick="toWords()" />
            <p id="demo"></p>
            <p id="demo1"></p>
        </body>
    </html> 
    
    0 讨论(0)
  • 2020-11-22 15:54

    Another conversion that uses remainders and supports different languages:

    function numberToWords(number) {
      var result = [];
    
      var fraction = number.toFixed(2).split('.');
      var integer_part = parseInt(fraction[0]);
      // var fractional_part = parseInt(fraction[1]); -- not handled here
    
      var previousNumber = null;
      for (var i = 0; i < fraction[0].length; i++) {
        var reminder = Math.floor(integer_part % 10);
        integer_part /= 10;
        var name = getNumberName(reminder, i, fraction[0].length, previousNumber);
        previousNumber = reminder;
        if (name)
          result.push(name);
      }
    
      result.reverse();
      return result.join(' ');
    }
    

    The getNumberName function is language-dependent and handles numbers up to 9999 (but it is easy to extend it to handle larger numbers):

    function getNumberName(number, power, places, previousNumber) {
      var result = "";
      if (power == 1) {
        result = handleTeensAndTys(number, previousNumber);
      } else if (power == 0 && places != 1 || number == 0) {
        // skip number that was handled in teens and zero
      } else {
        result = locale.numberNames[number.toString()] + locale.powerNames[power.toString()];
      }
    
      return result;
    }
    

    handleTeensAndTys handles multiples of ten:

    function handleTeensAndTys(number, previousNumber) {
      var result = "";
      if (number == 1) { // teens
        if (previousNumber in locale.specialTeenNames) {
          result = locale.specialTeenNames[previousNumber];    
        } else if (previousNumber in locale.specialTyNames) {
          result = locale.specialTyNames[previousNumber] + locale.teenSuffix;
        } else {
          result = locale.numberNames[previousNumber] + locale.teenSuffix;    
        }
      } else if (number == 0) { // previousNumber was not handled in teens
        result = locale.numberNames[previousNumber.toString()];
      } else { // other tys
        if (number in locale.specialTyNames) {
          result = locale.specialTyNames[number];
        } else {
          result = locale.numberNames[number];
        }
        result += locale.powerNames[1];
        if (previousNumber != 0) {
          result += " " + locale.numberNames[previousNumber.toString()];
        }
      }
      return result;
    }
    

    Finally, locale examples:

    var locale = { // English
      numberNames: {1: "one", 2: "two", 3: "three", 4: "four", 5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine" },
      powerNames: {0: "", 1: "ty", 2: " hundred", 3: " thousand" },
      specialTeenNames: {0: "ten", 1: "eleven", 2: "twelve" },
      specialTyNames: {2: "twen", 3: "thir", 5: "fif" },
      teenSuffix: "teen"
    };
    
    var locale = { // Estonian
      numberNames: {1: "üks", 2: "kaks", 3: "kolm", 4: "neli", 5: "viis", 6: "kuus", 7: "seitse", 8: "kaheksa", 9: "üheksa"},
      powerNames: {0: "", 1: "kümmend", 2: "sada", 3: " tuhat" },
      specialTeenNames: {0: "kümme"},
      specialTyNames: {},
      teenSuffix: "teist"
    };
    

    Here's a JSFiddle with tests: https://jsfiddle.net/rcrxna7v/15/

    0 讨论(0)
  • 2020-11-22 15:54
     var units = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
    var tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
    
    
    
    function convert7digitIntoWords(num) {
        var remainder = num % 1000000
        var hun = num - remainder;
        var div = Math.floor(num / 100000);
        if (remainder !== 0)
            return (convert2digitIntoWords(div) + " lakhs " + convert5digitIntoWords(remainder % 100000))
        else
            return (convert2digitIntoWords(div) + " lakhs ")
    }
    
    function convert6digitIntoWords(num) {
        var remainder = num % 100000
        var hun = num - remainder;
        var div = Math.floor(num / 100000);
        if (remainder !== 0)
            return (units[div] + " lakh " + convert5digitIntoWords(remainder))
        else
            return (units[div] + " lakh ")
    }
    
    function convert5digitIntoWords(num) {
        var remainder = num % 10000
        var hun = num - remainder;
        var div = Math.floor(num / 1000);
        if (remainder !== 0)
            return (convert2digitIntoWords(div) + " thousand " + convert3digitIntoWords(remainder % 1000))
        else
            return (convert2digitIntoWords(div) + " thousand")
    }
    
    function convert4digitIntoWords(num) {
        var remainder = num % 1000
        var hun = num - remainder;
        var div = Math.floor(num / 1000);
        if (remainder !== 0)
            return (units[div] + " thousand " + convert3digitIntoWords(remainder))
        else
            return (units[div] + " thousand")
    }
    
    
    function convert3digitIntoWords(num) {
        var remainder = num % 100
        var hun = num - remainder;
        var div = Math.floor(num / 100);
        if (remainder !== 0)
            return (units[div] + " hundred " + convert2digitIntoWords(remainder))
        else
            return (units[div] + " hundred ")
    }
    
    function convert2digitIntoWords(num) {
        var remainder = num % 10;
        var div = Math.floor(num / 10);
        return (tens[div] + " " + convertNumIntoWords(remainder));
    }
    
    function convertNumIntoWords(num) {
    
        switch (("" + num).length) {
            case 1:
                return units[num];
            case 2:
                return convert2digitIntoWords(num);
            case 3:
                return convert3digitIntoWords(num)
            case 4:
                return convert4digitIntoWords(num)
            case 5:
                return convert5digitIntoWords(num)
            case 6:
                return convert6digitIntoWords(num)
            case 7:
                return convert7digitIntoWords(num)
            default:
                return "cannot be converted"
        }
    }
    
    console.log(convertNumIntoWords(3445125));
    
    0 讨论(0)
  • 2020-11-22 15:55

    I've just written paisa.js to do this, and it handles lakhs and crores correctly as well, can check it out. The core looks a bit like this:

    const regulars = [
      {
        1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine'
      },
      {
        2: 'twenty', 3: 'thirty', 4: 'forty', 5: 'fifty', 6: 'sixty', 7: 'seventy', 8: 'eighty', 9: 'ninety'
      }
    ]
    
    const exceptions = {
      10: 'ten',
      11: 'eleven',
      12: 'twelve',
      13: 'thirteen',
      14: 'fourteen',
      15: 'fifteen',
      16: 'sixteen',
      17: 'seventeen',
      18: 'eighteen',
      19: 'nineteen'
    }
    
    const partInWords = (part) => {
      if (parseInt(part) === 0) return
      const digits = part.split('')
      const words = []
      if (digits.length === 3) {
        words.push([regulars[0][digits.shift()], 'hundred'].join(' '))
      }
      if (exceptions[digits.join('')]) {
        words.push(exceptions[digits.join('')])
      } else {
        words.push(digits.reverse().reduce((memo, el, i) => {
          memo.unshift(regulars[i][el])
          return memo
        }, []).filter(w => w).join(' '))
      }
      return words.filter(w => w.trim().length).join(' and ')
    }
    
    0 讨论(0)
  • 2020-11-22 15:56

    For those who are looking for imperial/english naming conventions.

    Based on @Salman's answer

    var a = ['','one ','two ','three ','four ', 'five ','six ','seven ','eight ','nine ','ten ','eleven ','twelve ','thirteen ','fourteen ','fifteen ','sixteen ','seventeen ','eighteen ','nineteen '];
    var b = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
    
    function inWords (num) {
        if ((num = num.toString()).length > 12) return 'overflow';
        n = ('00000000000' + num).substr(-12).match(/^(\d{3})(\d{3})(\d{3})(\d{1})(\d{2})$/);
        if (!n) return; var str = '';
        str += (n[1] != 0) ? (Number(n[1]) > 99 ? this.a[Number(n[1][0])] + 'hundred ' : '') + (a[Number(n[1])] || b[n[1][1]] + ' ' + a[n[1][2]]) + 'billion ' : '';
        str += (n[2] != 0) ? (Number(n[2]) > 99 ? this.a[Number(n[2][0])] + 'hundred ' : '') + (a[Number(n[2])] || b[n[2][1]] + ' ' + a[n[2][2]]) + 'million ' : '';
        str += (n[3] != 0) ? (Number(n[3]) > 99 ? this.a[Number(n[3][0])] + 'hundred ' : '') + (a[Number(n[3])] || b[n[3][1]] + ' ' + a[n[3][2]]) + 'thousand ' : '';
        str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
         str += (Number(n[5]) !== 0) ? ((str !== '') ? 'and ' : '') +
                    (this.a[Number(n[5])] || this.b[n[5][0]] + ' ' +
                        this.a[n[5][1]]) + '' : '';
        return str;
    }
    
    document.getElementById('number').onkeyup = function () {
        document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
    };
    <span id="words"></span>
    <input id="number" type="text" />

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