0

I'm using the following script to use dots as the thousands separator and commas as decimals separator that I got from this question.

var numero = 1000.00;

function formatThousands(n, dp) {
    var s = ''+(Math.floor(n)),
        d = n % 1,
        i = s.length,
        r = '';
    while ((i -= 3) > 0) {
        r = '.' + s.substr(i, 3) + r;
    }

    return s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
}

alert(formatThousands(numero,2));
/// http://jsperf.com/compare-two-format-thousands

See also jsfiddle

This is working OK, except for integers. For example, the number 1000 will return 1.000 and I want it to return 1.000,00 since the numbers refer to Euro currency.

How can I add the 2 decimals (cents) in every number?

Thanks for helping!

Community
  • 1
  • 1
  • 1
    possible duplicate of [How can I format numbers as money in JavaScript?](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – Bergi Feb 06 '14 at 17:42
  • @Bergi Yes, I found the answer to the question in your link! –  Feb 06 '14 at 17:56
  • As mentioned above, I found the answer to this question [here][1]. [1]: http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript –  Feb 06 '14 at 17:57

1 Answers1

0

Does this work?

function formatThousands(n, dp) {
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = '.' + s.substr(i, 3) + r; }
  s = s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
  return s.charAt(-1) != ',' ? s+',00' : s;
}

EDIT:

How about this?

function formatThousands(n, dp) {
  n = (''+n).split('.');
  i = n[0];
  d = !(n[1]) ? '00' : n[1];
  n = i.match(/.{4}/g).join('.');
  return n + ',' + d;
}

http://jsfiddle.net/XC3sS/12/

bearfriend
  • 10,322
  • 3
  • 22
  • 28
  • It works only if the number is integer. If it is for example 1000.01 it doenst' work –  Feb 06 '14 at 17:47