PHP:支持区域设置的数字格式 [英] PHP: Locale aware number format

查看:55
本文介绍了PHP:支持区域设置的数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要为我的网站访问者设置号码3253454.

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

如果我使用内置的number_format函数,则会得到:3,253,454,这对英国和美国非常有用,但是大多数其他国家/地区使用3.253.454

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

我有很多国际访客.

有人可以给我指出这里的最佳实践吗?

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

理想情况下,我希望获取浏览器的语言环境并相应地设置数字格式.在PHP中甚至可能吗?

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

推荐答案

如果要部署本地化的网站,则需要确保您

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);

然后我们修改上面的函数number_format_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.

这篇关于PHP:支持区域设置的数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆