javascript - Comment formater les numéros en tant que chaîne de devises

Mots clés : javascriptformattingcurrencyjavascript

meilleur 5 Réponses javascript - Comment formater les numéros en tant que chaîne de devises

vote vote

93

// Create our number formatter. var formatter = new Intl.NumberFormat('en-US', {   style: 'currency',   currency: 'USD',    // These options are needed to round to whole numbers if that's what you want.   //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)   //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501) });  formatter.format(2500); /* $2,500.00 */ 
(2500).toLocaleString('en-US', {   style: 'currency',   currency: 'USD', }); /* $2,500.00 */ 
vote vote

83

  const profits = 2489.8237;    profits.toFixed(3) // Returns 2489.824 (rounds up)   profits.toFixed(2) // Returns 2489.82   profits.toFixed(7) // Returns 2489.8237000 (pads the decimals) 
function formatMoney(number, decPlaces, decSep, thouSep) {     decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,     decSep = typeof decSep === "undefined" ? "." : decSep;     thouSep = typeof thouSep === "undefined" ? "," : thouSep;     var sign = number < 0 ? "-" : "";     var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));     var j = (j = i.length) > 3 ? j % 3 : 0;      return sign +         (j ? i.substr(0, j) + thouSep : "") +         i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +         (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : ""); }  document.getElementById("b").addEventListener("click", event => {   document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); });
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p>
(123456789.12345).formatMoney(2, ".", ","); 
(123456789.12345).formatMoney(2); 
    d = d == undefined ? "," : d,     t = t == undefined ? "." : t, 
function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {   try {     decimalCount = Math.abs(decimalCount);     decimalCount = isNaN(decimalCount) ? 2 : decimalCount;      const negativeSign = amount < 0 ? "-" : "";      let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();     let j = (i.length > 3) ? i.length % 3 : 0;      return       negativeSign +       (j ? i.substr(0, j) + thousands : '') +       i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +       (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");   } catch (e) {     console.log(e)   } };  document.getElementById("b").addEventListener("click", event => {   document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value); });
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label> <br /> <button id="b">Get Output</button> <p id="x">(press button to get output)</p>
vote vote

75

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67 
1        --> "1.00" 12       --> "12.00" 123      --> "123.00" 1234     --> "1,234.00" 12345    --> "12,345.00" 123456   --> "123,456.00" 1234567  --> "1,234,567.00" 12345.67 --> "12,345.67" 
/**  * Number.prototype.format(n, x)  *   * @param integer n: length of decimal  * @param integer x: length of sections  */ Number.prototype.format = function(n, x) {     var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';     return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,'); };  1234..format();           // "1,234" 12345..format(2);         // "12,345.00" 123456.7.format(3, 2);    // "12,34,56.700" 123456.789.format(2, 4);  // "12,3456.79" 
/**  * Number.prototype.format(n, x, s, c)  *   * @param integer n: length of decimal  * @param integer x: length of whole part  * @param mixed   s: sections delimiter  * @param mixed   c: decimal delimiter  */ Number.prototype.format = function(n, x, s, c) {     var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',         num = this.toFixed(Math.max(0, ~~n));      return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ',')); };  12345678.9.format(2, 3, '.', ',');  // "12.345.678,90" 123456.789.format(4, 4, ' ', ':');  // "12 3456:7890" 12345678.9.format(0, 3, '-');       // "12-345-679" 
vote vote

65

Number((someNumber).toFixed(1)).toLocaleString() 
someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}); 
const money = new Intl.NumberFormat('de-CH',   { style:'currency', currency: 'CHF' }); const percent = new Intl.NumberFormat('de-CH',   { style:'percent', maximumFractionDigits: 1, signDisplay: "always"}); 
money.format(1234.50); // output CHF 1'234.50 percent.format(0.083);  // output +8.3% 
vote vote

57

/* decimal_sep: character used as decimal separator, it defaults to '.' when omitted thousands_sep: char used as thousands separator, it defaults to ',' when omitted */ Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep) {    var n = this,    c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal    d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)     /*    According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]    the fastest way to check for not defined parameter is to use typeof value === 'undefined'    rather than doing value === undefined.    */    t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value     sign = (n < 0) ? '-' : '',     // Extracting the absolute value of the integer part of the number and converting to string    i = parseInt(n = Math.abs(n).toFixed(c)) + '',     j = ((j = i.length) > 3) ? j % 3 : 0;    return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); } 
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals) alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());  // Some tests (do not forget parenthesis when using negative numbers and number with no decimals) alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3)); 

Questions similaires