JavaScript中是否有将函数转换为特定区域设置格式的功能?

Mur*_*dvi 37 javascript numbers currency

是否有内置的JavaScript函数将字符串转换为特定的语言环境(在我的情况下是欧元)?

例如50.00应该转换为50,00 €.

Wil*_*Wit 33

我在这个页面找到了一种方法.

你可以在toLocaleString不使用toFixed之前使用它.toFixed返回一个字符串,toLocaleString应该得到一个数字.但是你可以传递一个options对象toLocaleString,该选项minimumFractionDigits可以帮助你完成功能toFixed.

50.toLocaleString('de-DE', {
    style: 'currency', 
    currency: 'EUR', 
    minimumFractionDigits: 2 
});
Run Code Online (Sandbox Code Playgroud)

检查您可以使用此功能传递的所有其他选项.


Mat*_*all 20

50.00是一个无单位的价值.您可以做的最好的事情是转换50.0050,00然后追加自己.因此,只需使用Number.toLocaleString().

var i = 50.00;
alert(i.toLocaleString() + ' €'); // alerts '50.00 €' or '50,00 €'
Run Code Online (Sandbox Code Playgroud)

演示→

很多相关问题:

  • 这不起作用.调用toFixed(2)后,返回一个字符串.所以你在字符串而不是整数上调用toLocaleString(),这不包括在法语中将'12 .34'改为'12,34'. (3认同)
  • 不幸的是@TvdH仍然不适用于'50`. (3认同)
  • 可以将.toFixed()的结果解析回浮点数,然后运行,例如parseFloat((12.3456).toFixed(2))。toLocaleString() (2认同)
  • 这不是开箱即用的 - toFixed()返回一个字符串,toLocalString需要一个数字.使用:`price.toLocaleString(.culture,{minimumFractionDigits:2,maximumFractionDigits:2});` (2认同)

Seb*_*ner 10

ECMAScript Internationalization API中描述了与语言环境相关的功能.

要将float 50.0转换为字符串50,00 €(使用'de-DE'语言环境),您需要编写:

new Intl.NumberFormat("de-DE", {style: "currency", currency: "EUR"}).format(50.0)
Run Code Online (Sandbox Code Playgroud)

此API在所有当前主流浏览器中均可用.

有关Internationalization API的数字格式化功能的更多信息,请阅读MDN上文章.

  • 对于现代 JavaScript 来说,这是一个很好的解决方案。有没有相反的方法呢? (2认同)

Luk*_*uke 8

我正在一个处理多种货币的国际网站上工作.

每次我想显示货币时,我都不想处理设置Locale,所以我做了一个原型,将货币格式化为适当的区域设置.它的转换是透明的,因此您也可以根据自己的需要进行自定义.

Number.prototype.formatMoney = function(moneySymbol, decimalCharacter, thousandsCharacter, decimalPlaces, symbolLocation)
{
    var symbolLocation = (symbolLocation == undefined || symbolLocation < 1 || symbolLocation == "begin")?"begin":"end";
    var decimalPlaces = isNaN(decimalPlaces = Math.abs(decimalPlaces)) ? 2 : decimalPlaces;
    var thisNumber = parseFloat(this, decimalPlaces);
    var decimalCharacter = decimalCharacter == undefined ? "." : decimalCharacter;
    var thousandsCharacter = thousandsCharacter == undefined ? "," : thousandsCharacter;
    //var pm = thisNumber < 0 ? "-" : "";
    var pm = "";
    var pmB = thisNumber < 0 ? "(" : "";
    var pmE = thisNumber < 0 ? ")" : "";
    var i = parseInt(thisNumber = Math.abs(+thisNumber || 0)) + "";
    var j = (j = i.length) > 3 ? j % 3 : 0;
    var retString = pmB;
    retString += ((symbolLocation == "begin")?((moneySymbol)?moneySymbol+"":""):"");
    retString += pm;
    retString += (j ? i.substr(0, j) + thousandsCharacter : "")
    retString += i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousandsCharacter);
    //alert((decimalPlaces ? decimalCharacter + (Math.ceil(Math.abs(thisNumber - i)*Math.pow(10, decimalPlaces))/Math.pow(10, decimalPlaces)).toFixed(decimalPlaces).slice(decimalPlaces) : "") + '\n' + Math.abs(thisNumber - i).toFixed(6));
    retString += (decimalPlaces ? decimalCharacter + (Math.ceil(Math.abs(thisNumber - i).toFixed(6)*Math.pow(10, decimalPlaces))/Math.pow(10, decimalPlaces)).toFixed(decimalPlaces).slice(decimalPlaces) : "");
    retString += ((symbolLocation == "end")?((moneySymbol)?moneySymbol+"":""):"");
    retString += pmE;
    return  retString;
};
Number.prototype.formatMoneyInternational = function(languageCode, inputCode)
{
    var languageCode = languageCode == undefined ? 'en_us' : languageCode;
    var inputCode = inputCode == undefined ? languageCode : inputCode;
    var currencies = {
        'float':    {'symbol':null,         'symbolPosition': 'end',        'decimal':'.',  'comma': ''},       //Float
        //Arabic - Saudi Arabia ?(1025): Sorry, the server does not support this locale 
        //Arabic - Iraq ?(2049): Sorry, the server does not support this locale 
        //Arabic - Egypt ?(3073): Sorry, the server does not support this locale 
        //Arabic - Algeria ?(5121): Sorry, the server does not support this locale 
        'bg':       {'symbol':' BGN',       'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Bulgarian 
        'ca':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Catalan 
        //Chinese - Traditional (1028): Sorry, the server does not support this locale 
        //Chinese - Simplified (2052): Sorry, the server does not support this locale 
        'cs':       {'symbol':' Kc',        'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Czech 
        'da':       {'symbol':'kr ',        'symbolPosition': 'begin',      'decimal':',',  'comma': '.'},      //Danish 
        'de':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //German - Germany 
        'de_au':    {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //German - Austrian 
        'de_lu':    {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //German - Luxembourg 
        'el':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Greek 
        'en_us':    {'symbol':'$',          'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //English - United States 
        'en_gb':    {'symbol':'£ ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //English - United Kingdom 
        'en_au':    {'symbol':'$ ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //English - Australia 
        'en_ca':    {'symbol':'$',          'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //English - Canadian 
        'en_ie':    {'symbol':'€ ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //English - Irish 
        'es_mx':    {'symbol':'$ ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //Spanish - Mexico 
        'es':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Spanish - International 
        'fi':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Finnish 
        'fr':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //French - France 
        'fr_ca':    {'symbol':' $',         'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //French - Canadian 
        'fr_ch':    {'symbol':'SFr. ',      'symbolPosition': 'begin',      'decimal':'.',  'comma': '\''}, //French - Swiss 
        //Hebrew ?(1037): Sorry, the server does not support this locale 
        'hu':       {'symbol':' Ft',        'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Hungarian 
        'it':       {'symbol':'€ ',         'symbolPosition': 'begin',      'decimal':',',  'comma': '.'},      //Italian - Italy 
        'it_ch':    {'symbol':'&#8355; ',       'symbolPosition': 'begin',      'decimal':'.',  'comma': '\''}, //Italian - Swiss 
        'ja':       {'symbol':'¥ ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': '\''}, //Japanese 
        //Korean (1042): Sorry, the server does not support this locale 
        'nl':       {'symbol':'€ ',         'symbolPosition': 'begin',      'decimal':',',  'comma': '.'},      //Dutch - Netherlands 
        'no':       {'symbol':'kr ',        'symbolPosition': 'begin',      'decimal':',',  'comma': ' '},      //Norwegian 
        'pl':       {'symbol':' zl',        'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Polish 
        'pt_br':    {'symbol':'R$ ',        'symbolPosition': 'begin',      'decimal':',',  'comma': '.'},      //Portuguese - Brazil 
        'pt':       {'symbol':' €',         'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Portuguese - Standard 
        'ro':       {'symbol':' lei',       'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Romanian 
        'ru':       {'symbol':' p.',        'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Russian 
        'hr':       {'symbol':' kn',        'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Croatian 
        'sr':       {'symbol':' Din.',      'symbolPosition': 'end',        'decimal':',',  'comma': '.'},          //Serbian - Latin 
        //'sr': {'symbol':' ???. ', 'symbolPosition': 'end',    'decimal':',',  'comma': '.'},          //Serbian - Cyrillic 
        'sv':       {'symbol':' kr',        'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Swedish 
        //Thai (1054): Sorry, the server does not support this locale 
        'tr':       {'symbol':' TL',        'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Turkish 
        'id':       {'symbol':' Rp.',       'symbolPosition': 'begin',      'decimal':' ',  'comma': '.'},      //Indonesian 
        'uk':       {'symbol':' rpH.',      'symbolPosition': 'end',        'decimal':',',  'comma': ' '},          //Ukranian 
        'be':       {'symbol':' p.',        'symbolPosition': 'end',        'decimal':',',  'comma': ' '},      //Belausian 
        'sl':       {'symbol':' SIT',       'symbolPosition': 'end',        'decimal':',',  'comma': '.'},          //Slovenian 
        'et':       {'symbol':' kr',        'symbolPosition': 'end',        'decimal':'.',  'comma': ' '},      //Estonian 
        'lv':       {'symbol':'Ls ',        'symbolPosition': 'begin',      'decimal':',',  'comma': ' '},      //Latvian 
        'lt':       {'symbol':' Lt',        'symbolPosition': 'end',        'decimal':',',  'comma': '.'},      //Lithuanian 
        //Farsi ?(1065): Sorry, the server does not support this locale 
        //Vietnamese (1066): Sorry, the server does not support this locale 
        'af':       {'symbol':'R ',         'symbolPosition': 'begin',      'decimal':'.',  'comma': ','},      //Afrikaans 
        'fo':       {'symbol':'kr ',        'symbolPosition': 'begin',      'decimal':',',  'comma': '.'}       //Faeroese
    };
    var currencyString = this+"";
    if(currencies[languageCode])
    {
        //alert(currencyString.replace(currencies[inputCode].comma, '').replace(currencies[inputCode].decimal, '.').replace(/[^\d\.\,\-]/g, ''));
        var currencyNumber = parseFloat(currencyString.replace(currencies[inputCode].comma, '').replace(currencies[inputCode].decimal, '.').replace(/[^\d\.\,\-]/g, ''));
        return currencyNumber.formatMoney(currencies[languageCode].symbol, currencies[languageCode].decimal, currencies[languageCode].comma, 2, currencies[languageCode].symbolPosition);
    }
    else
    {
        var currencyNumber = parseFloat(currencyString.replace(currencies['en_us'].decimal, '.').replace(currencies['en_us'].comma, '').replace(/[^\d\.\,\-]/g, ''));
        alert('Error: '  + languageCode + ' country code unknown.');
        return currencyNumber.formatMoney(currencies['en_us'].symbol, currencies['en_us'].decimal, currencies['en_us'].comma, 2, currencies['en_us'].symbolPosition);
    }
}
String.prototype.formatMoneyInternational = Number.prototype.formatMoneyInternational;
Run Code Online (Sandbox Code Playgroud)


sma*_*ajl 6

Matt Ball接受的答案是错误的 - 不知道为什么没有人注意到.没有String.toLocaleString() [ref]这样的功能!因此,当Number.toFixed()返回String时,结果toLocaleString()什么都不做.所以你不会得到本地化的数字,只是toFixed()功能的产物.

错了(不要这样做):

var i = 1234.123;
alert(i.toFixed(2).toLocaleString() + ' €'); // ALWAYS alerts '1234.12 €' (no locale formatting)
Run Code Online (Sandbox Code Playgroud)

建议如何做对:

您可以使用像NumberFormatter这样的jQuery插件.