PHP: Locale aware number format(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?
推荐答案
如果您要部署本地化网站,您需要确保 setlocale().为了重复 yaauie 的上述帖子,我会在您的初始化代码中添加类似以下代码片段的内容:
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:区域设置感知数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP:区域设置感知数字格式


- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01