How to separate numbers from three to three, backwards in JavaScript, without regular expression?

3

I already know how to separate the numbers of three in three, backwards, with regular expression in JavaScript .

But I would like to know if there is a simpler solution in JavaScript, and without the use of regular expression.

For example:

1000; // 1.000
10000; // 10.000
10000000; // 10.000.000

How could I do this?

    
asked by anonymous 06.02.2017 / 12:05

2 answers

6

toLocaleString() does this.

function separarDeTresEmTres(numero) {
    return numero.toLocaleString();
}


console.log(separarDeTresEmTres(1000));  
console.log(separarDeTresEmTres(1000000));
console.log(separarDeTresEmTres(10000000));
    
06.02.2017 / 12:22
4

In the "nail", I created this function that converts the number to String to be able to traverse the elements, and then use #

var n1 = 1000; // 1.000
var n2 = 10000; // 10.000
var n3 = 100000; // 100.000
var n4 = 1000000; // 1.000.000
var n5 = 10000000; // 10.000.000


function formatarTresEmTres(n) {
  n = n.toString();
  var nFormatado = '';
  for (var i = n.length; i > 0; i = i - 3) {
    nFormatado += '.' + n.substring(i - 3, i);
  };
  return nFormatado.split(".").slice(1).reverse().join(".");
}

console.log(formatarTresEmTres(n1), formatarTresEmTres(n2), formatarTresEmTres(n3), formatarTresEmTres(n4),  formatarTresEmTres(n5));
    
06.02.2017 / 13:16