在 PHP 中打印货币数字格式
我的页面中要显示一些价格值。
我正在编写一个函数,它接受浮动价格并返回带货币代码的格式化货币 val。
例如,fnPrice(1001.01)
应该打印 $ 1,000.01
I have some price values to display in my page.
I am writing a function which takes the float price and returns the formatted currency val with currency code too..
For example, fnPrice(1001.01)
should print $ 1,000.01
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
最简单的答案是
number_format()
。如果您希望您的应用程序能够使用多种货币和区域设置感知格式(例如,对于我们一些欧洲人来说
1.000,00
),它会变得有点复杂。有
money_format()
但它在 Windows 上不起作用并且依赖于setlocale()
,在我看来这是垃圾,因为它需要在服务器端安装(任意命名的)语言环境包。如果您想认真地国际化您的应用程序,请考虑使用成熟的国际化库,例如 Zend Framework 的 Zend_Locale 和 Zend_Currency。
The easiest answer is
number_format()
.If you want your application to be able to work with multiple currencies and locale-aware formatting (
1.000,00
for some of us Europeans for example), it becomes a bit more complex.There is
money_format()
but it doesn't work on Windows and relies onsetlocale()
, which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.
通过 PHP 5.3+ 中的 intl 扩展,您可以使用 NumberFormatter 类:
打印:
with the intl extension in PHP 5.3+, you can use the NumberFormatter class:
which prints :
sprintf() 是用于各种字符串格式化的 PHP 函数
http://php.net/manual/en/function.sprintf.php
我使用这个函数:
sprintf() is the PHP function for all sorts of string formatting
http://php.net/manual/en/function.sprintf.php
I use this function:
我构建了这个小函数来自动将任何内容格式化为良好的货币格式。
编辑
有人指出,这不显示负值。我将其分成两行,以便更容易编辑格式。如果它是负值,则将其括在括号中:
I built this little function to automatically format anything into a nice currency format.
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
参考链接: https://www.php.net/manual/en /function.number-format.php
输出为:1,235.56
如果输出中不需要逗号。请删除函数内的逗号。
例如
输出为:1235.56
Reference Link : https://www.php.net/manual/en/function.number-format.php
The output is : 1,235.56
If you don't need comma in output.Please remove comma inside function.
For example
The output is : 1235.56
来自 文档
From the docs
(PHP 5 >= 5.3.0、PHP 7、PHP 8、PECL intl >= 1.0.0)
输出将为
https://www.php.net/manual/en/numberformatter.formatcurrency.php
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
output will be
https://www.php.net/manual/en/numberformatter.formatcurrency.php
PHP 有一个名为
money_format
的函数来执行此操作。请此处了解此内容。PHP has a function called
money_format
for doing this. Read about this here.