Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

internationalization - PHP: Locale aware number format

I want to format the number 3253454 for my website visitors.

If I use the inbuilt number_format function, I get: 3,253,454 which is great for UK and USA, however most other countries use 3.253.454

I have many international visitors.

Can anyone give me a pointer to the best practice here?

Ideally I wish to get the browser's locale and format the number accordingly. Is this even possible in PHP?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...