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.
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.
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, " ");
}
See this answer for the original function
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.