JavaScript 中是否有将值转换为特定语言环境格式的功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5314237/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a functionality in JavaScript to convert values into specific locale formats?
提问by Murtaza Mandvi
Is there a built in function of JavaScript to convert a string into a particular locale (Euro in my case)?
是否有内置的 JavaScript 函数可以将字符串转换为特定的语言环境(在我的情况下为欧元)?
E.g. 50.00
should get converted to 50,00
.
例如,50.00
应该转换为50,00
.
采纳答案by Matt Ball
50.00
is a unit-less value. The best you can do is convert 50.00
to 50,00
and then append the yourself. Therefore, just use
Number.toLocaleString()
.
50.00
是一个无单位的值。您能做的最好的事情是转换50.00
为50,00
然后附加自己。因此,只需使用
Number.toLocaleString()
.
var i = 50.00;
alert(i.toLocaleString() + ' '); // alerts '50.00 ' or '50,00 '
Lots of relevant questions:
很多相关问题:
- How can I format numbers as money in JavaScript?(the big one; ~70k views)
- Convert to currency format
- Format currency using javascript
- how do i print currency format in javascript
- JavaScript: Format number/currency w/regards to culture like .NET's String.Format()?(possibly useful, if you're using ASP.NET)
- format number to price
- 如何在 JavaScript 中将数字格式化为货币?(最大的;~70k 次观看)
- 转换为货币格式
- 使用 javascript 格式化货币
- 我如何在 javascript 中打印货币格式
- JavaScript:使用 .NET 的 String.Format() 等文化格式化数字/货币?(可能有用,如果您使用的是 ASP.NET)
- 将数字格式化为价格
回答by Willem de Wit
I found a way to do this at this page.
You can you toLocaleString
without using toFixed
before it. toFixed
returns a string, toLocaleString
should get a number. But you can pass an options object with toLocaleString
, the option minimumFractionDigits
could help you with the functionality toFixed
has.
你可以toLocaleString
不使用toFixed
它之前。toFixed
返回一个字符串,toLocaleString
应该得到一个数字。但是您可以使用 传递选项对象toLocaleString
,该选项minimumFractionDigits
可以帮助您实现功能toFixed
。
50.toLocaleString('de-DE', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
});
Checkout all the other options you can pass with this function.
检查您可以使用此函数传递的所有其他选项。
回答by Sebastian Zartner
There are locale related features described within the ECMAScript Internationalization API.
ECMAScript 国际化 API 中描述了与语言环境相关的功能。
To get the float 50.0
converted to the string 50,00
(using the 'de-DE' locale) you need to write this:
要将浮点数50.0
转换为字符串50,00
(使用“de-DE”语言环境),您需要这样写:
new Intl.NumberFormat("de-DE", {style: "currency", currency: "EUR"}).format(50.0)
This API is available in all current major browsers.
此 API 在当前所有主要浏览器中均可用。
For more info about the number formatting features of the Internationalization API you should read the article at MDN.
回答by Luke
I am working on an international site which deals with multiple currencies.
我在一个处理多种货币的国际网站上工作。
I didn't want to deal with setting the Locale every time I wanted to display a currency, so instead I made a prototype which formats the currency to the appropriate locale. It is transparent in its conversions so you can customize it to your needs as well.
我不想每次想显示货币时都设置语言环境,所以我制作了一个原型,将货币格式化为适当的语言环境。它的转换是透明的,因此您也可以根据需要对其进行自定义。
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, "" + 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':'₣ ', '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;
回答by smajl
The accepted answer from Matt Ball is wrong- dunno why nobody haven't noticed. There is no such function as String.toLocaleString()
[ref]!Therefore when Number.toFixed()
returns String, the consequent toLocaleString()
does nothing. So you won't get localized number, just the product of toFixed()
function.
马特鲍尔接受的答案是错误的- 不知道为什么没有人注意到。没有String.toLocaleString()
[ref] 之类的功能!因此,当Number.toFixed()
返回 String 时,结果toLocaleString()
什么都不做。所以你不会得到本地化的数字,只是toFixed()
功能的乘积。
WRONG (don't do it like this):
错误(不要这样做):
var i = 1234.123;
alert(i.toFixed(2).toLocaleString() + ' '); // ALWAYS alerts '1234.12 ' (no locale formatting)
Suggestion how to do it right:
建议如何正确执行:
You may use jQuery plugin like NumberFormatter.
你可以使用像NumberFormatter这样的 jQuery 插件。
回答by Andrew Moore
Built-in, yes and no. There is Number.toLocaleString()
but it is dependent on the system's locale.
内置,是和否。有,Number.toLocaleString()
但它取决于系统的语言环境。
However, there are some libraries which have modules for this. MooTools's Locale.Numberfor example allows you to convert a number into different locales (adding your own locale is trivial).
但是,有一些库具有用于此的模块。例如MooTools的Locale.Number允许您将数字转换为不同的语言环境(添加您自己的语言环境很简单)。
Locale.use("EU");
var inEuros = (50).formatCurrency(); // 50,00
If you want the sign to be printed after, you can simply create your own locale:
如果您希望在之后打印标志,您可以简单地创建自己的语言环境:
Locale.define('EU-suffix', 'Number', {
currency: {
suffix: ' '
}
}).inherit('EU', 'Number');
回答by spacebiker
For javascript use the accounting library http://openexchangerates.github.io/accounting.js/Then you can do:
对于 javascript 使用会计库http://openexchangerates.github.io/accounting.js/然后你可以这样做:
// Default usage:
accounting.formatMoney(12345678); // ,345,678.00
// European formatting (custom symbol and separators), can also use options object as second parameter:
accounting.formatMoney(4999.99, "", 2, ".", ","); // 4.999,99
// Negative values can be formatted nicely:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// Simple `format` string allows control of symbol position (%v = value, %s = symbol):
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
回答by patrykgruszka
I have prepared small library to deal with currency formatting - money
我准备了小型图书馆来处理货币格式——钱
money(1000.5, 'EUR'); // -> 1 000.50
money(1000.5, 'USD'); // -> ,000.50
money(1000.5, 'PLN'); // -> 1 000,50 z?
Supported currency (ISO codes): PLN, EUR, USD, GBP, JPY, CZK, SEK
支持的货币(ISO 代码):PLN、EUR、USD、GBP、JPY、CZK、SEK
回答by Ben Schenker
Some of the other answers are okay but I would recommend a different library, NumeralJSover Number.toLocaleString because the latter is not supported widely in all browsers (it breaks on even new versions of safari). NumeralJS is really powerful and supports anything you would want to do with converting numbers to strings.
其他一些答案还可以,但我会推荐一个不同的库,NumeralJS 而不是 Number.toLocaleString,因为后者在所有浏览器中都没有得到广泛支持(它甚至在新版本的 safari 上都会中断)。NumeralJS 非常强大,支持您将数字转换为字符串的任何操作。
First, set the language (I chose french) and then format it:
首先,设置语言(我选择法语),然后格式化:
numeral.language('fr');
numeral(50.00).format('0.00 $');
Outputs:
输出:
"50,00 "
The website explains it quite well and has tons of examples.
该网站对其进行了很好的解释,并提供了大量示例。