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.