Formatting numbers with jQuery

Asked

Viewed 1,506 times

5

Hello,

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

Example:

Standard values

-> 2569
-> 192544694

How I wish they were formatted

-> 2.569
-> 192.544.694

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

Any solution? Be it a script or alternative framework?

  • Are these numbers, or money? (About formatting money: http://answall.com/q/11018/129)

  • @Sergio, are numbers!

  • Okay, so my answer should do what you need. Take a look.

3 answers

8


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 as we want to group backwards, hence the logic of reverse().

  • 1

    No pimples, very good

2

  • +1 very good...

0

  • is it my impression or in this library does not have formatting for numbers? Despite that, very interesting, thanks for the suggestion!

Browser other questions tagged

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