Regular Expression - Help with Repetition in Regex

I’m trying to format a number for display on a label.
The ideia is to add a thounsands separator.

So numbers like: 1000, 1000000 or 100000000
Result in: 1.000, 1.000.000 and 100.000.000 respectively.

I have a solution base on the (\d\d\d) pattern but it only works for thousands, not for millions or thounsand millions or for billions.

Granted I could hard code the thing for billions and would most probably never reach the case of failure. But I’m a perfecionist at heart.

Here’s my code.

var re = /(\d+)(\d\d\d)+$/;
var newStr = elements['lbl_credit_acum'].text.replace(re, "$1.$2");
elements['lbl_credit_acum'].text = newStr;

newStr = elements['lbl_inv_acum'].text.replace(re, "$1.$2");
elements['lbl_inv_acum'].text = newStr;

Txs for the help Mr. Regex Guru.
Best,
Miguel

Here’s the solution I come up with. Unfortunately much more verbose than I expected. I have a feeling this could be done with much less code using regular expression fully but I ran into a brick wall when tried to use {1-3} in the regular expression. I couldn’t get Servoy to accept it!

Maybe there’s an issue here.

So here’s an acceptable solution, albeit a little verbose, but abstract solution:

// format the labels with the thousand separator!
// gather the labels to format in an Array
var labelsToFormat = [elements['lbl_credit_acum'], elements['lbl_inv_acum']]
var re = /(\d\d\d)$/;
var idx = 0;
var newStr = [];
var tempStr = '';
var head = '';
var tail = '';

for ( var i=0; i < labelsToFormat.length; i++ ) {
  tempStr = labelsToFormat[i].text;
  idx = tempStr.search(re);

  while (idx != -1) {
    head = tempStr.substr(0,idx);
    tail = tempStr.substr(idx);

    if ( head ) {
      newStr.unshift('.' + tail);
    }
    else { 
      newStr.unshift(tail);
      break;
    }

    tempStr = head;
    idx = tempStr.search(re);

  }
  newStr.unshift(head);
  labelsToFormat[i].text = newStr.join('');
  newStr = [];
}

Miguel

Miguel,

What about this one:

var newStr = elements['lbl_inv_acum'].text;
elements['lbl_inv_acum'].text = utils.numberFormat(newStr * 1, "#,###");

Marcel,

I guess it’s a little less verbose :wink:
Txs for the tip.

Miguel