PHP:区域设置感知数字格式

PHP: Locale aware number format(PHP:区域设置感知数字格式)
本文介绍了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:区域设置感知数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)