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

2022-01-12 00:00:00 currency formatting php

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

How do you convert a number to a string showing dollars and cents?

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'

这个函数实际上有很多选项,请转到我链接的文档查看它们.

This function actually has tons of options, go to the documentation I linked to to see them.

注意:money_format 在 Windows 中未定义.

Note: money_format is undefined in Windows.

更新:通过 PHP 手册:https://www.php.net/manual/en/function.money-format.php

UPDATE: Via the PHP manual: https://www.php.net/manual/en/function.money-format.php

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

WARNING: This function [money_format] has been DEPRECATED as of PHP 7.4.0. Relying on this function is highly discouraged.

相反,请查看 NumberFormatter::formatCurrency.

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

相关文章