Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

php number_format not using locale

It's a first for me, using setLocale, I usually hate using it because I work on shared hosting, but since changing job recently, I have gained server control and thus the ability to install locales.

When I switch to fr_CA on my application, I call

money_format('%n', $value)

And it formats the currency correctly, but strangely, if I

number_format($value, 2);

I get a number formatted with the correct amount of decimals (2) but the decimal separator is not what was expected. I'm getting "0.32" instead of "0,32" like the locale says.

I even checked the locale on the server, and it clearly shows that the decimal separator is a comma:

LC_NUMERIC
decimal_point             "<U002C>"
thousands_sep             "<U0020>"
grouping                  3;3
END LC_NUMERIC

I checked online and U002C is indead comma... not period...

What's your take on this?

PS, here's what i checked:

  1. setLocale does return fr_CA
  2. setLocale clearly formats correctly and my code is not overriding the symbols in the call to number_format

Thanks

Upvotes: 0

Views: 1246

Answers (1)

Mark Baker
Mark Baker

Reputation: 212412

The alternative is to use localeconv() to retrieve that information and use it in number_format(), something like:

$locale = localeconv(); 
echo number_format(
    $number, 
    $locale['frac_digits'], 
    $locale['decimal_point'], 
    $locale['thousands_sep']
);

Upvotes: 1

Related Questions