How can I convert an integer into its verbal representation?

后端 未结 14 2301
走了就别回头了
走了就别回头了 2020-11-22 15:23

Is there a library or a class/function that I can use to convert an integer to it\'s verbal representation?

Example input:

4,567,788`

14条回答
  •  臣服心动
    2020-11-22 16:09

    In case anyone wants a JavaScript version

    Number.prototype.numberToWords = function () {
        var unitsMap = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
        var tensMap = ["zero", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
    
        var num = this.valueOf();
        if (Math.round(num == 0)) {
            return "zero";
        }
        if (num < 0) {
            var positivenum = Math.abs(num);
            return "minus " + Number(positivenum).numberToWords();
        }
        var words = "";
        if (Math.floor(num / 1000000) > 0) {
            words += Math.floor(num / 1000000).numberToWords() + " million ";
            num = Math.floor(num % 1000000);
        }
        if (Math.floor(num / 1000) > 0) {
            words += Math.floor(num / 1000).numberToWords() + " thousand ";
            num = Math.floor(num % 1000);
        }
        if (Math.floor(num / 100) > 0) {
            words += Math.floor(num / 100).numberToWords() + " hundred ";
            num = Math.floor(num % 100);
        }
        if (Math.floor(num > 0)) {
            if (words != "") {
                words += "and ";
            }
            if (num < 20) {
            words += unitsMap[num];
            }
            else {
                words += tensMap[Math.floor(num / 10)];
                if ((num % 10) > 0) {
                    words += "-" + unitsMap[Math.round(num % 10)];
                }
            }
        }
        return words.trim();
    }
    

提交回复
热议问题