Belmin Belmin - 1 year ago 102
Javascript Question

Format numbers with apostrophe as thousands separator

I have number from API provided in this way 774317 and I have to convert it to this value 774'317.00, so if there are 2 more decimals they should be separated with full stop like this

77431745 => 774'317.45

Following this answer I make it to separate thousands (so It format it to this 774'317), but last 2 decimals are issue for me, because I'm not very good with RegEX.Below is code that I used for this

convertMonetary(value) {
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "'")

Answer Source

The question is not very explicit in exactly when the last two digits are not decimals and .00 needs to be added, and when the last two digits are decimals and only a . needs to be added in the right place.

The code below assumes that with 6 or fewer digits, the .00 need to be added, otherwise the last 2 digits are seen as decimals and a . is added.

When you run it, the first 2 rows are your example data, the lower 2 rows are examples where I added a 1 before the number to demonstrate how numbers of those lengths get treated.

function convertMonetary(inp) {
  return inp.replace(/^(\d*?\d{1,6})(\d{2})?$/, function(m, whole, dec) {
    return whole.replace(/\B(?=(\d{3})+(?!\d))/g, "'") + ((dec!=undefined)?'.'+dec:'.00');

document.getElementById('outp').value = 
  '77431745  => ' + convertMonetary('77431745') + '\n' +
  '774317    => ' + convertMonetary('774317') + '\n\n' +
  '177431745 => ' + convertMonetary('177431745') + '\n' +
  '1774317   => ' + convertMonetary('1774317')
<textarea id="outp" rows="10" style="width:100%"></textarea>

To explain a bit why the regex is the way it is:

(\d*?\d{1,6}) might make little sense on first sight, why not just do \d+. The thing is that the {1,6} quantifier of the latter \d is greedy, the first \d's quantifier *? is not, this makes that (\d{2})? only gets matched when there are more than 6 digits in a row.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download