Existe-t-il une fonctionnalité en JavaScript pour convertir des valeurs en formats locaux spécifiques?

Existe-t-il une fonction intégrée de JavaScript pour convertir une chaîne en une locale particulière (Euro dans mon cas)?

Par exemple, 50.00 devraient être convertis à 50,00 € .

    50.00 est une valeur sans unité. Le meilleur que vous pouvez faire est de convertir 50.00 à 50,00 , puis ajoutez l' vous-même. Par conséquent, utilisez simplement Number.toLocaleString() .

     var i = 50.00; alert(i.toLocaleString() + ' €'); // alerts '50.00 €' or '50,00 €' 

    Démonstration →

    Beaucoup de questions pertinentes:

    • Comment puis-je formater des nombres en argent sous JavaScript? (Le grand, ~ 70k vues)
    • Convertir en format de devise
    • Format de devise en utilisant javascript
    • Comment imprimer le format de la devise dans javascript
    • JavaScript: Format du numéro / de la devise w en ce qui concerne la culture comme le String.Format () de .NET? (Éventuellement utile, si vous utilisez ASP.NET)
    • Numéro de format au prix

    J'ai trouvé un moyen de le faire sur cette page .

    Vous pouvez vous toLocaleString à toLocaleString sans l'utiliser avant de l' toLocaleString . toFixed renvoie une chaîne, toLocaleString devrait obtenir un numéro. Mais vous pouvez passer un objet d'options avec toLocaleString , l'option minimumFractionDigits peut vous aider avec la fonctionnalité toFixed a.

     50.toLocaleString('de-DE', { style: 'currency', currency: 'EUR', minimumFractionDigits: 2 }); 

    Cochez toutes les autres options que vous pouvez passer avec cette fonction.

    Je travaille sur un site international qui traite de multiples devises.

    Je ne voulais pas régler le paramètre local chaque fois que je voulais afficher une devise, alors j'ai créé un prototype qui forme la devise dans les paramètres régionaux appropriés. Il est transparent dans ses conversions afin que vous puissiez le personnaliser à vos besoins.

     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; 

    La réponse acceptée de Matt Ball est erronée – ne sais pas pourquoi personne n'a remarqué. Il n'existe pas de fonction telle que String.toLocaleString() [ref] ! Par conséquent, lorsque Number.toFixed() renvoie String, conséquente toLocaleString() ne fait rien. Donc, vous n'obtiendrez pas le numéro localisé, juste le produit de la fonction toFixed() .

    Mauvais (ne le fais pas comme ça):

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

    Suggestion pour le faire correctement:

    Vous pouvez utiliser le plugin jQuery comme NumberFormatter .

    Il existe des fonctionnalités liées aux paramètres régionaux décrites dans l' API d'internationalisation d'ECMAScript .

    Pour obtenir le flotteur 50.0 converti à la chaîne 50,00 € (en utilisant les paramètres régionaux 'de-DE'), vous devez l'écrire:

     new Intl.NumberFormat("de-DE", {style: "currency", currency: "EUR"}).format(50.0) 

    Cette API est disponible dans tous les principaux navigateurs actuels.

    Pour plus d'informations sur les fonctionnalités de formatage des numéros de l'API d'internationalisation, lisez l' article chez MDN .

    Intégré, oui et non. Il existe Number.toLocaleString() mais il dépend des paramètres régionaux du système.

    Cependant, il existe des bibliothèques qui ont des modules pour cela. Le numéro de Locale.Number de MooTools vous permet par exemple de convertir un nombre en différents paramètres régionaux (en ajoutant que votre propre localité est trivial).

     Locale.use("EU"); var inEuros = (50).formatCurrency(); // € 50,00 

    JsFiddle Demo


    Si vous souhaitez que le signe € soit imprimé après, vous pouvez simplement créer vos propres paramètres régionaux:

     Locale.define('EU-suffix', 'Number', { currency: { suffix: ' €' } }).inherit('EU', 'Number'); 

    Certaines des autres réponses sont correctes, mais je recommanderais une librairie différente, NumeralJS sur Number.toLocaleString, car ce dernier n'est pas largement pris en charge dans tous les navigateurs (il se brise même sur de nouvelles versions de safari). NumeralJS est vraiment puissant et prend en charge tout ce que vous voulez faire avec la conversion de nombres en cordes.

    Tout d'abord, définissez la langue (j'ai choisi le français) puis formatez-la:

     numeral.language('fr'); numeral(50.00).format('0.00 $'); 

    Les sorties:

     "50,00 €" 

    Le site Web l'explique assez bien et compte beaucoup d'exemples.

    Pour javascript, utilisez la bibliothèque comptable http://openexchangerates.github.io/accounting.js/ Ensuite, vous pouvez:

     // Default usage: accounting.formatMoney(12345678); // $12,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 

    J'ai préparé une petite bibliothèque pour faire face au formatage de la monnaie – argent

     money(1000.5, 'EUR'); // -> 1 000.50 € money(1000.5, 'USD'); // -> $1,000.50 money(1000.5, 'PLN'); // -> 1 000,50 zł 

    Monnaie supportée (codes ISO): PLN, EUR, USD, GBP, JPY, CZK, SEK