【问题标题】:Is there any function in Javascript for converting numbers (with decimal places) to words?Javascript中是否有将数字(带小数位)转换为单词的功能?
【发布时间】:2020-02-26 07:04:00
【问题描述】:

我想将计算出的数量转换为单词。

保留 2 到 3 位小数,因为金额以美元(例如 230.54)和阿曼里亚尔(例如 230.542)为单位。 我尝试了 Stackoverflow 中提到的一个函数,但它没有小数点后 3 位。即Convert digits into words with JavaScript 但这些函数要么不能用于小数位,要么不包括 3 个小数位。

例如,如果数字是 235.45,那么单词应该是 TWO HUNDRED THIRTY FIVE AND 45 CENTS 或者 TWO HUNDRED THIRTY FIVE AND 45/100 DOLLARS Omari Riyals 相同:如果金额为 235.456,则 TWO HUNDRED THIRTY FIVE AND 456 FILS 或者 TWO HUNDRED THIRTY FIVE AND 450/1000 RIYALS

我试过了,但它只输出小数点前的数字:

function converttoWords(amount) {
    var words = new Array();
    words[0] = '';
    words[1] = 'One';
    words[2] = 'Two';
    words[3] = 'Three';
    words[4] = 'Four';
    words[5] = 'Five';
    words[6] = 'Six';
    words[7] = 'Seven';
    words[8] = 'Eight';
    words[9] = 'Nine';
    words[10] = 'Ten';
    words[11] = 'Eleven';
    words[12] = 'Twelve';
    words[13] = 'Thirteen';
    words[14] = 'Fourteen';
    words[15] = 'Fifteen';
    words[16] = 'Sixteen';
    words[17] = 'Seventeen';
    words[18] = 'Eighteen';
    words[19] = 'Nineteen';
    words[20] = 'Twenty';
    words[30] = 'Thirty';
    words[40] = 'Forty';
    words[50] = 'Fifty';
    words[60] = 'Sixty';
    words[70] = 'Seventy';
    words[80] = 'Eighty';
    words[90] = 'Ninety';
    amount = amount.toString();
    var atemp = amount.split(".");
    var number = atemp[0].split(",").join("");
    var n_length = number.length;
    var words_string = "";
    if (n_length <= 9) {
      var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
      var received_n_array = new Array();
      for (var i = 0; i < n_length; i++) {
        received_n_array[i] = number.substr(i, 1);
      }
      for (var i = 9 - n_length, j = 0; i < 9; i++ , j++) {
        n_array[i] = received_n_array[j];
      }
      for (var i = 0, j = 1; i < 9; i++ , j++) {
        if (i == 0 || i == 2 || i == 4 || i == 7) {
          if (n_array[i] == 1) {
            n_array[j] = 10 + parseInt(n_array[j]);
            n_array[i] = 0;
          }
        }
      }
      value = "";
      for (var i = 0; i < 9; i++) {
        if (i == 0 || i == 2 || i == 4 || i == 7) {
          value = n_array[i] * 10;
        } else {
          value = n_array[i];
        }
        if (value != 0) {
          words_string += words[value] + " ";
        }
        if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
          words_string += "Crores ";
        }
        if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
          words_string += "Lakhs ";
        }
        if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
          words_string += "Thousand ";
        }
        if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
          //words_string += "Hundred and ";
          words_string += "Hundred ";
        } else if (i == 6 && value != 0) {
          words_string += "Hundred ";
        }
      }
      words_string = words_string.split("  ").join(" ");
    }
    return words_string;
}

谁能帮帮我?

【问题讨论】:

  • 看起来您只需要截断为整数,将整数转换为单词,然后将小数部分转换为适当的分数或“CENTS”/“FILS”文本并附加。你试过什么?
  • 到目前为止您尝试过什么?你被困在哪里了?
  • @nico 我尝试开发这个(编辑我的问题),但它只输出小数点前的金额。
  • @curiousKido 答案发布供您使用和投票

标签: javascript function suitescript2.0


【解决方案1】:

看看N/format/i18n 模块。可以根据 ISO 639-2 代码设置语言环境。

在浏览器控制台中试试这个;

var i18n;   
require(['N/format/i18n'],
  function(i8) {
    i18n = i8;
  });               
i18n.spellOut({number: 145.32, locale:'eng'});

【讨论】:

    【解决方案2】:

    2022 年 2 月:通用和短“货币到单词”Javascript 函数

    用英语处理所有货币


    我开发了以下简短的 Javascript 函数,可以将任何货币数字转换为包括小数位(分数)在内的单词。

    该函数使用美国英语语法将数字写入单词。

    语法

    currencyToWords(number, currancy, format={})
    
    number    : any numeric or number in string form for large numbers
    currency  : object holding the currency information as follows:
                {
                 country    : the country Name       (e.g.: 'US')
                 majorSingle: Major Unit Single Name (e.g.: 'Dollar')
                 majorPlural: Major Unit Plural Name (e.g.: 'Dollars')
                 minorSingle: Minor Sub-Unit Single  (e.g.: 'Cent')
                 minorPlural: Minor Sub-Unit Plural  (e.g.: 'Cents')
                 fraction   : Decimal Places Number  (e.g.: 2)
                 };
    format    : object holding the format for the minor (sub-units) using
                'minor' parameters, as follows:
                'numeric' : Sub-Units in Numeric Form (i.g. 35 Cents)
                'fraction': Sub-Units in Fractional Form (i.g. 35/100 US Dollar)
                empty or other (default): Sub-Units in Words Form
    ----------------------------------------------------------------------------
    

    示例 1:在默认模式下转换美元

        let currancy = {
        country    : "US",     // country Name
        majorSingle: "Dollar", // Major Unit Single
        majorPlural: "Dollars",// Major Unit Plural
        minorSingle: "Cent",   // Minor Sub-Unit Single
        minorPlural: "Cents",  // Minor Sub-Unit Plural
        fraction   : 2,        // Decimal Places
        };
    
    console.log(currencyToWords(50,currancy));
    // Fifty US Dollars
    
    console.log(currencyToWords(20.23,currancy));
    // Twenty US Dollars, and Twenty-Three Cents
    
    console.log(currencyToWords(0.99,currancy));
    // Zero US Dollar, and Ninety-Nine Cents
    
    console.log(currencyToWords(100.2,currancy));
    // One Hundred US Dollars, and Twenty Cents
    
    console.log(currencyToWords(1.01,currancy));
    // One US Dollar, and One Cent
    
    console.log(currencyToWords(0.01,currancy));
    // Zero US Dollar, and One Cent
    
    console.log(currencyToWords(520.01,currancy));
    // Five Hundred Twenty US Dollars, and One Cent
    

    示例 2:使用“数字”格式的子单位(次要)转换美元

    console.log(currencyToWords(50,currancy,{minor:"numeric"}));
    // Fifty US Dollars
    
    console.log(currencyToWords(20.23,currancy,{minor:"numeric"}));
    // Twenty US Dollars, and 23 Cents
    
    console.log(currencyToWords(0.99,currancy,{minor:"numeric"}));
    // Zero US Dollar, and 99 Cents
    
    console.log(currencyToWords(100.2,currancy,{minor:"numeric"}));
    // One Hundred US Dollars, and 20 Cents
    
    console.log(currencyToWords(1.01,currancy,{minor:"numeric"}));
    // One US Dollar, and 1 Cent
    
    console.log(currencyToWords(0.01,currancy,{minor:"numeric"}));
    // Zero US Dollar, and 1 Cent
    
    console.log(currencyToWords(520.01,currancy,{minor:"numeric"}));
    // Five Hundred Twenty US Dollars, and 1 Cent
    

    示例 2:使用“分数”格式的子单位(次要)转换美元

    console.log(currencyToWords(50,currancy,{minor:"fraction"}));
    // Fifty US Dollars
    
    console.log(currencyToWords(20.23,currancy,{minor:"fraction"}));
    // Twenty, and 23/100 US Dollars
    
    console.log(currencyToWords(0.99,currancy,{minor:"fraction"}));
    // Zero, and 99/100 US Dollar
    
    console.log(currencyToWords(100.2,currancy,{minor:"fraction"}));
    // One Hundred, and 20/100 US Dollars
    
    console.log(currencyToWords(1.01,currancy,{minor:"fraction"}));
    // One, and 1/100 US Dollar
    
    console.log(currencyToWords(0.01,currancy,{minor:"fraction"}));
    // Zero, and 1/100 US Dollar
    
    console.log(currencyToWords(520.01,currancy,{minor:"fraction"}));
    // Five Hundred Twenty, and 1/100 US Dollars
    

    更改货币

    您可以指定国家名称、主要和次要货币名称(单数和复数)。 fraction 是次要(子单元)的小数位数。对于美元,欧元是 2:2,科威特第纳尔:3,或阿曼里亚尔:3,等等。

    如果您想使用没有国家名称的货币,请将国家名称设置为空字符串 ''。

    /********************************************************
    * @function    : currencyToWords(number, currancy, [format])
    * @purpose     : Converts Currency to Words
    * @version     : 1.00
    * @author      : Mohsen Alyafei
    * @licence     : MIT
    * @date        : 27 Feb 2022
    * @param       : number   [required] numeric or string
    *                curr [required] object description
    *                format   [optional] with the following parameters:
    *                minor: 'numeric' or 'fraction' or none (default)
    * @returns     : {string} Currency String in Words
    ********************************************************/
    function currencyToWords(num=0, curr, format={}) {
    format=format.minor;
    format ??= "";
    num=(num+="").split((0.1).toLocaleString().substring(1,2));
    let frc = (num[1]+"000").substring(0,curr.fraction), a=", and ",
        cc  = " "+curr.country+(curr.country?" ":"")+(num[0]>1?curr.majorPlural:curr.majorSingle),
        out = numToWords(num[0])+(format=="fraction" && num[1]?"":cc);
    if (num[1]) {
        let sub=frc>1?curr.minorPlural:curr.minorSingle;
        if      (format=="numeric")  out+=a+(+frc)+" "+sub;
        else if (format=="fraction") out+=a+(+frc)+"/1"+"0".repeat(curr.fraction)+cc;
        else    out+=a+numToWords(frc)+" "+sub;
    }
    return out;
    //----------------------------------------------------------------
    function numToWords(num = 0) {
    if (num == 0) return "Zero";
    num= ("0".repeat(2*(num+="").length%3)+num).match(/.{3}/g);
    let out="",
        T10s=["","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"],
        T20s=["","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"],
        sclT=["","Thousand","Million","Billion","Trillion","Quadrillion"];
    return num.forEach((n,i) => {
    if (+n) {
     let h=+n[0], t=+n.substring(1), scl=sclT[num.length-i-1];
     out+=(out?" ":"")+(h?T10s[h]+" Hundred":"")+(h && t?" ":"")+(t<20?T10s[t]:T20s[+n[1]]+(+n[2]?"-":"")+T10s[+n[2]]);
     out+=(out && scl?" ":"")+scl;
    }}),out;
    }
    }
    //----------------------------------------------------------------
    
    
    
    
    
    
    
    
    
    
    //=========================================
    //             Test Code
    //=========================================
    
    let currancy = {
    country    : "US",     // country Name
    majorSingle: "Dollar", // Major Unit Single
    majorPlural: "Dollars",// Major Unit Plural
    minorSingle: "Cent",   // Minor Sub-Unit Single
    minorPlural: "Cents",  // Minor Sub-Unit Plural
    fraction   : 2,        // Decimal Places
    };
    
    // default. sub-units in word format
    console.log(currencyToWords(50,currancy));
    console.log(currencyToWords(20.23,currancy));
    console.log(currencyToWords(0.99,currancy));
    console.log(currencyToWords(100.2,currancy));
    console.log(currencyToWords(1.01,currancy));
    console.log(currencyToWords(0.01,currancy));
    console.log(currencyToWords(520.01,currancy));
    console.log("-".repeat(50));
    
    // sub-units in numeric format
    console.log(currencyToWords(50,currancy,{minor:"numeric"}));
    console.log(currencyToWords(20.23,currancy,{minor:"numeric"}));
    console.log(currencyToWords(0.99,currancy,{minor:"numeric"}));
    console.log(currencyToWords(100.2,currancy,{minor:"numeric"}));
    console.log(currencyToWords(1.01,currancy,{minor:"numeric"}));
    console.log(currencyToWords(0.01,currancy,{minor:"numeric"}));
    console.log(currencyToWords(520.01,currancy,{minor:"numeric"}));
    console.log("-".repeat(50));
    
    // sub-units in fractional format
    console.log(currencyToWords(50,currancy,{minor:"fraction"}));
    console.log(currencyToWords(20.23,currancy,{minor:"fraction"}));
    console.log(currencyToWords(0.99,currancy,{minor:"fraction"}));
    console.log(currencyToWords(100.2,currancy,{minor:"fraction"}));
    console.log(currencyToWords(1.01,currancy,{minor:"fraction"}));
    console.log(currencyToWords(0.01,currancy,{minor:"fraction"}));
    console.log(currencyToWords(520.01,currancy,{minor:"fraction"}));
    console.log("-".repeat(50));
    
    currancy = {
        country    : "Omani",  // country Name
        majorSingle: "Riyal", // Major Unit Single
        majorPlural: "Riyals",// Major Unit Plural
        minorSingle: "Baisa",  // Minor Sub-Unit Single
        minorPlural: "Baisa",  // Minor Sub-Unit Plural
        fraction   : 3,        // Decimal Places
        };
    
    console.log(currencyToWords(50,currancy,{minor:"fraction"}));
    console.log(currencyToWords(200.234,currancy,{minor:"fraction"}));
    console.log(currencyToWords(2000.99,currancy,{minor:"fraction"}));
    console.log(currencyToWords(30100.2,currancy,{minor:"fraction"}));
    console.log(currencyToWords(3456.001,currancy,{minor:"fraction"}));
    console.log(currencyToWords(500.01,currancy,{minor:"fraction"}));
    console.log(currencyToWords(22.1,currancy,{minor:"fraction"}));
    console.log(currencyToWords(0.45,currancy,{minor:"fraction"}));

    【讨论】:

      猜你喜欢
      • 2021-12-06
      • 1970-01-01
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多