如何在 PHP 中将数字格式化为美元金额

问题描述 投票:0回答:8

如何将数字转换为显示美元和美分的字符串?

eg:
123.45    => '$123.45'
123.456   => '$123.46'
123       => '$123.00'
.13       => '$0.13'
.1        => '$0.10'
0         => '$0.00'
php formatting currency
8个回答
90
投票

如果您只想要简单的东西:

'$' . number_format($money, 2);

数字格式()


87
投票

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

警告:自 PHP 7.4.0 起,此函数 [money_format] 已被弃用。强烈建议不要依赖此功能。

相反,请查看 NumberFormatter::formatCurrency

    $number = "123.45";
    $formatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
    return $formatter->formatCurrency($number, 'USD');

17
投票

我尝试了

money_format()
,但它对我来说根本不起作用。然后我尝试了以下一个。它对我来说很完美。希望它也能以正确的方式为你工作..:)

你应该使用这个

number_format($money, 2,'.', ',')

它将以货币格式显示货币编号,最多 2 位小数。


9
投票

请注意,在 PHP 7.4 中,money_format() 函数已被弃用。它可以被 intl NumberFormatter 功能替换,只需确保启用 php-intl 扩展即可。这只是少量的努力,而且是值得的,因为您可以获得很多可定制性。

$f = new NumberFormatter("en", NumberFormatter::CURRENCY);
$f->formatCurrency(12345, "USD"); // Outputs "$12,345.00"

仍然适用于 7.4 的快速方法如 Darryl Hein 所提到的:

'$' . number_format($money, 2);

8
投票

在 PHP 和 C++ 中,您可以使用 printf() 函数

printf("$%01.2f", $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);

0
投票
/*     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)

0
投票

如果您确实想将数字转换为货币格式的值。请参考PHP: number_format

带参数的函数定义如下:

number_format( float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = "," ): string

用法示例:

  1. '$'。数字格式(123.32134, 2);
  2. '$'。数字格式(247, 2);
  3. '$'。数字格式(247, 2);
© www.soinside.com 2019 - 2024. All rights reserved.