Formatting numbers with jQuery

5

Hello,

I have an array that is returned through an AJAX request and I want to format the numbers for each of these keys as follows:

  

Example:

Default values

-> 2569
-> 192544694

How would you like them to be formatted

-> 2.569
-> 192.544.694

Of course this formatting would be through a function because it is a variable value. I created a function but did not get total flexibility in its effectiveness, in addition to trying some frameworks, such as number.js , for example.

Any solution? Is it an alternative script or framework?

    
asked by anonymous 29.12.2016 / 21:47

3 answers

7

You can do it like this:

function formatar(nr) {
  return String(nr)
    .split('').reverse().join('').split(/(\d{3})/).filter(Boolean)
    .join('.').split('').reverse().join('');
}

var numeros = [2569, 192544694];
var formatados = numeros.map(formatar);
console.log(JSON.stringify(formatados)); // ["2.569","192.544.694"]

The idea is to use a regular expression to group 3 by 3, but how do we want to group from back to front, hence the logic of reverse() .

    
29.12.2016 / 22:01
2
function format(nStr)
{
    nStr += '';
    x = nStr.split(',');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + '.' + '$2');
    }
    return x1 + x2;
}

Abe Miessler Credits at link

    
29.12.2016 / 21:51
1

I recommend the library jQuery mask . Your code might look like this:

HTML

<input class="money" />

jQuery

 $('.money').mask('0000.000,00', {reverse: true});

JSFiddle : link

    
29.12.2016 / 21:51