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

Asked

Viewed 728 times

5

2 answers

7


  • 1

    Really? I’m ashamed to have used a regular expression now :p

4

In "nail", I created this function that converts the number into String to be able to traverse the elements, and then use the substring to go cutting and riding every three.

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));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.