我想为我的网站访问者设置数字 3253454 的格式。
如果我使用内置的 number_format 函数,我会得到:3,253,454,这对英国和美国来说非常有用,但大多数其他国家/地区使用 3.253.454
我有很多国际访客。
任何人都可以给我指点这里的最佳实践吗?
理想情况下,我希望获取浏览器的区域设置并相应地设置数字格式。这在 PHP 中可能吗?
如果您要部署本地化网站,您需要确保setlocale()。 为了重复 yaauie 的上述帖子,我会在初始化代码中添加类似以下代码片段的内容:
$locale = ( isset($_COOKIE['locale']) ) ?
$_COOKIE['locale'] :
$_SERVER['HTTP_ACCEPT_LANGUAGE'];
setlocale(LC_ALL, $locale);
然后我们修改上面的函数
number_format_locale()
,看起来像这样:
function number_format_locale($number,$decimals=2) {
$locale = localeconv();
return number_format($number,$decimals,
$locale['decimal_point'],
$locale['thousands_sep']);
}
当然,这是在理想的情况下,根据您部署到的平台以及您安装的区域设置文件的版本,您可能需要针对一些不规则之处进行编码。 但设置区域设置将有助于金钱、数字和日期。
也许尝试独立于为所有脚本设置全局区域设置的方法?
获取用户的区域设置:
$locale = ( isset($_COOKIE['locale']) ) ?
$_COOKIE['locale'] :
$_SERVER['HTTP_ACCEPT_LANGUAGE'];
格式化数字:
我建议使用PHP NumberFormatter。这是一种 OOP 方法,使用 ICU 库。
$formatStyle=NumberFormatter::DECIMAL;
$formatter= new NumberFormatter($locale, $formatStyle);
echo $formatter->format(3253454);//proper output depending on locale
您可以在那里使用许多不同的样式格式,例如:小数、货币或百分比。阅读更多这里。
这是数字格式化的最佳方式,因为它依赖于全局Unicode Common Locale Data Repository。
string number_format (float $number, int $decimals, string $dec_point, string $thousands_sep)
另一个有用的链接可能是来自 Zend Framework 的 Zend_Locale - 它可以检测用户的语言,还可以帮助进行数字/货币格式设置
PHP 同时提供了一个 NumberFormatter 类,它非常适合此目的:
来自 https://www.php.net/manual/en/function.number-format.php#76448:
<?php
function strtonumber( $str, $dec_point=null, $thousands_sep=null )
{
if( is_null($dec_point) || is_null($thousands_sep) ) {
$locale = localeconv();
if( is_null($dec_point) ) {
$dec_point = $locale['decimal_point'];
}
if( is_null($thousands_sep) ) {
$thousands_sep = $locale['thousands_sep'];
}
}
$number = (float) str_replace($dec_point, '.', str_replace($thousands_sep, '', $str));
if( $number == (int) $number ) {
return (int) $number;
} else {
return $number;
}
}
?>
这似乎正是您正在寻找的。 :)
在我的项目中我使用 Zend Framework。在这种情况下,我使用这样的东西:
$locale = new Zend_Locale('fr_FR');
$number = Zend_Locale_Format::toNumber(2.5, array('locale' => $locale));
// will return 2,5
print $number;
您可以使用 HTTP_ACCEPT_LANGUAGE 服务器变量来猜测它们的区域设置和预期的数字格式。
如果我要实现这个,我将允许用户设置首选项来覆盖猜测,我的函数将如下所示:
function number_format_locale($number,$decimals=2) {
$locale = ( isset($_COOKIE['locale']) ?
$_COOKIE['locale'] :
$_SERVER['HTTP_ACCEPT_LANGUAGE']
)
switch($locale) {
case 'en-us':
case 'en-ca':
$decimal = '.';
$thousands = ',';
break;
case 'fr':
case 'ca':
case 'de':
case 'en-gb':
$decimal = ',';
$thousands = ' ';
break;
case 'es':
case 'es-mx':
default:
$decimal = ',';
$thousands = ' ';
}
return $number_format($number,$decimals,$decimal,$thousands);
}