PHP: Locale aware number format PHP: Locale aware number format php php

PHP: Locale aware number format


If you're deploying a localized website, you're going to want to make sure you setlocale(). To riff off of yaauie's above post I'd add something like the following code snippet in your initialization code:

$locale = ( isset($_COOKIE['locale']) ) ?             $_COOKIE['locale'] :             $_SERVER['HTTP_ACCEPT_LANGUAGE'];setlocale(LC_ALL, $locale);

Then we modify the above function number_format_locale(), to look like so:

function number_format_locale($number,$decimals=2) {    $locale = localeconv();    return number_format($number,$decimals,               $locale['decimal_point'],               $locale['thousands_sep']); }

Of course that's in an ideal world, depending on the platform you deploy to, and what version of the locale files you have installed, you might have to code around some irregularities. But setting locale is going to help with money, numbers, and dates.


Maybe try approach independent from setting global locale for all scripts?

Get user's locale:

$locale = ( isset($_COOKIE['locale']) ) ?             $_COOKIE['locale'] :             $_SERVER['HTTP_ACCEPT_LANGUAGE'];

Format the number:

I recommend using PHP NumberFormatter. It's an OOP approach which uses ICU library.

$formatStyle=NumberFormatter::DECIMAL;$formatter= new NumberFormatter($locale, $formatStyle);echo $formatter->format(3253454);//proper output depending on locale

You can use many different style formats there, for example: DECIMAL, CURRENCY or PERCENT. Read more here.

It's best way of number formatting, because it depends on global Unicode Common Locale Data Repository.


string number_format (float $number, int $decimals, string $dec_point, string $thousands_sep)

see php doku for number_format

Another helpful link may be Zend_Locale from Zend Framework - it can detect your user's language and also help with number/currency formatting