如何将数字转换为显示美元和美分的字符串?
eg:
123.45 => '$123.45'
123.456 => '$123.46'
123 => '$123.00'
.13 => '$0.13'
.1 => '$0.10'
0 => '$0.00'
如何将数字转换为显示美元和美分的字符串?
eg:
123.45 => '$123.45'
123.456 => '$123.46'
123 => '$123.00'
.13 => '$0.13'
.1 => '$0.10'
0 => '$0.00'
PHP 也有money_format()。
这是一个例子:
echo money_format('$%i', 3.4); // echos '$3.40'
这个函数实际上有很多选项,请转到我链接到的文档来查看它们。
注意:money_format 在 Windows 中未定义。
更新:通过 PHP 手册:https ://www.php.net/manual/en/function.money-format.php
警告:此函数 [ money_format ] 自 PHP 7.4.0 起已弃用。强烈建议不要依赖此功能。
相反,请查看NumberFormatter::formatCurrency。
$number = "123.45";
$formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
return $formatter->formatCurrency($number, 'USD');
我试过 money_format()
了,但它根本不适合我。然后我尝试了以下一个。它对我来说很完美。希望它也能以正确的方式为你工作.. :)
你应该使用这个
number_format($money, 2,'.', ',')
它将以货币格式显示货币数字,最多小数点后 2 位。
在 PHP 和 C++ 中,您可以使用 printf() 函数
printf("$%01.2f", $money);
请注意,在 PHP 7.4 中,money_format() 函数已弃用。它可以被 intl NumberFormatter 功能替换,只需确保启用 php-intl 扩展。这是一个很小的努力,而且值得,因为您可以获得很多可定制性。
$f = new NumberFormatter("en", NumberFormatter::CURRENCY);
$f->formatCurrency(12345, "USD"); // Outputs "$12,345.00"
Darryl Hein提到了仍然适用于 7.4 的快速方法:
'$' . number_format($money, 2);
在 php.ini 添加这个(如果它丢失):
#windows
extension=php_intl.dll
#linux
extension=php_intl.so
然后这样做:
$amount = 123.456;
// for Canadian Dollars
$currency = 'CAD';
// for Canadian English
$locale = 'en_CA';
$fmt = new \NumberFormatter( $locale, \NumberFormatter::CURRENCY );
echo $fmt->formatCurrency($amount, $currency);
/* Just Do the following, */
echo money_format("%(#10n","123.45"); //Output $ 123.45
/* If Negative Number -123.45 */
echo money_format("%(#10n","-123.45"); //Output ($ 123.45)