2

In PHP I can:

$number = 1234.56;
$nombre_format_francais = number_format($number, 2, '.', ' ');

and this shows me:

1 234.56

How can I make it in jQuery? I would like add separator.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
marksoodrig
  • 39
  • 1
  • 3
  • 1
    I prefer do this [the hard way, see for example this question](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) but you can use [a library, see this question](http://stackoverflow.com/questions/1068284/format-numbers-in-javascript). – Denys Séguret Apr 18 '13 at 15:38
  • You'll have to convert the number to a string first - JavaScript doesn't recognize numbers with separators in them. – Blazemonger Apr 18 '13 at 15:38
  • Or use a JavaScript implementation of PHP's number_format(); http://phpjs.org/functions/number_format/ – pmayer Apr 18 '13 at 16:04

3 Answers3

1

I did some searching, but this is really all I could come up with as there is no built in method:

Create the number

var num = 1234.56;

Format the decimal places - only necessary with longer decimals...

var result = num.toFixed(2); 

Add the spaces

result = numberWithSpace(result);

function numberWithSpace(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
}

Working Fiddle

See this answer for the original function

Community
  • 1
  • 1
What have you tried
  • 11,018
  • 4
  • 31
  • 45
1
function addSpaces(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;
}

just took it from here and adapted it.

Le_Morri
  • 1,619
  • 14
  • 18
1

The jQuery library does not have number localization features, but there is Globalize.js, which was originally developed as a localization plug-in to jQuery but was changed to an independent library. It includes predefined numeric formats for many languages and an easy way to modify or add them.

Using Globalize.js, you could e.g. first call Globalize.culture('fr'), and after this, Globalize.format(number) would yield the number as formatted by French conventions. It would produce the correct format, such as “1 234,56” (French uses decimal comma, not decimal point).

There are also other libraries for similar purposes. The choice between them depends, among other things, on the scope of localization in your projects – is it just about number format localization, or something wider.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390