1
\$\begingroup\$

I have a function that formats a number (even a float) to a German decimal format. I got this function from here https://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript and it works. But every time I want to format a number that I stored in a variable I have to add .format(2, 3, '.', ',').

EX: I have an int :45122.9 and I want to format it I have this function:

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 || ','));
};
var netto=45122.9;
document.write(netto.format(2, 3, '.', ',')+ ' ' +'€');

This will format my number as such 45.122,90 €.

Is there a way to name the function, let´s say... "formatNumber", add this part to it format(2, 3, '.', ',') and than just call it like this: document.write(formatNumber(netto)); ?

\$\endgroup\$

closed as off-topic by ratchet freak, SuperBiasedMan, Mast, Elias Van Ootegem, Quill Oct 14 '15 at 13:44

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "Questions must involve real code that you own or maintain. Pseudocode, hypothetical code, or stub code should be replaced by a concrete example. Questions seeking an explanation of someone else's code are also off-topic." – Mast, Elias Van Ootegem, Quill
  • "Questions containing broken code or asking for advice about code not yet written are off-topic, as the code is not ready for review. After the question has been edited to contain working code, we will consider reopening it." – ratchet freak, SuperBiasedMan
If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ Did or didn't you write this code yourself? Is the indentation intentional or a copy-paste error? \$\endgroup\$ – Mast Oct 14 '15 at 10:20
  • \$\begingroup\$ I already said I have the code from stackoverflow and the indentation is a copy-paste error. \$\endgroup\$ – Daria M Oct 14 '15 at 10:24
  • \$\begingroup\$ Aside from making it better, which I think there is room for improvement in terms of readability, I would suggest placing it in it's own CurrencyFormatter class. stackoverflow.com/questions/14034180/… \$\endgroup\$ – Nolo Oct 14 '15 at 10:28
  • \$\begingroup\$ @Nolo I do not know what you mean \$\endgroup\$ – Daria M Oct 14 '15 at 10:34
  • 1
    \$\begingroup\$ What happens if someone passes ',99}\\' as x to your function? It really would mess up your formatting, I suspect \$\endgroup\$ – Elias Van Ootegem Oct 14 '15 at 11:08
3
\$\begingroup\$

For formatting currency, given that there are many desired formats, the easiest and most readable way is to just make a function called formatCurrency() that might look something like this:

function formatCurrency(amount, symbol, groupDigits, preFixed, exchangeCommas){
    var result = amount.toFixed(2);
    if(groupDigits){
        result = result.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    if(prefixed){
        result = symbol + result;
    }else{
        result = result + symbol;
    }
    if(exchangeCommas){
        var decimalIndex = result.lastIndexOf(".");
        result = result.replace(",", ".");
        result = result.substring(0, decimalIndex) + "," + result.substring(decimalIndex + 1);
    }
    return result;
}

https://stackoverflow.com/questions/14467433/currency-formatting-in-javascript

Edit: Note that the parameters groupDigits, preFixed and exchangeCommas are optional boolean values.

Then if you want to make it shorter or less readable for whatever reason there are online tools that make it easy to do so, such as yui compressor.

\$\endgroup\$
1
\$\begingroup\$

My suggestion is:

/**
 * Formats given number according to given options.
 * @param {number} number The number to be formatted.
 * @param {!Object.<string, *>} options The formatting options.
 * @return {string} The formatted number string.
 */
function formatNumber(number, options) {
  /** @type {Array.<string>} */
  var result = (options['fraction'] ? number.toFixed(options['fraction']) :
                                      '' + number).split('.');
  return options['prefix'] +
      result[0].replace(/\B(?=(\d{3})+(?!\d))/g,
      /** @type {string} */ (options['grouping'])) +
      (result[1] ? options['decimal'] + result[1] : '') +
      options['suffix'];
}

// Example:
var expected = '45.122,90 €';
var number = 45122.9;
var formatted = formatNumber(number, {
  'decimal': ',',
  'grouping': '.',
  'fraction': 2,
  'prefix': '',
  'suffix': ' €'
 });


alert('Formatted: ' + formatted + '\n' +
      'Expected: ' + expected + '\n' +
      'Equals: ' + (formatted == expected));

Source: https://github.com/Datamart/Glize/blob/master/src/formatters/NumberFormatter.js#L22

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.