php - 如何让 NumberFormatter 打印带减号的负货币值?

标签 php currency numberformatter intl

我正在使用 PHP NumberFormatter 类来打印货币值。

例如:

  $cFormatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
  $cFormatter->formatCurrency(123, 'USD');
  $cFormatter->formatCurrency(123, 'BRL');
  $cFormatter->formatCurrency(123, 'GBP');

工作正常,并按预期分别返回 "$123.00"、"R$123.00"、"£123.00"。

但负数是以“会计风格”打印的,用方括号括起来,而不是前导减号“-”。

例如:

$cFormatter->formatCurrency(-456, 'USD');

返回 "($456.00)",而我想要 "-$456.00"。当然有一种简单的方法可以做到这一点?

我可以通过覆盖前缀和后缀来删除括号,如下所示:

$cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "-");
$cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_SUFFIX, "");

但是我没有得到货币符号,例如 "-456.00"

设置 NEGATIVE_PREFIX 属性时是否需要使用一些货币符号转义码?

编辑:我很乐意设置不同的语言环境,如果这能给我想要的结果的话。

编辑 2:查看 Intl library docs(用于实现 NumberFormatter 的库),以下看起来很有希望:

¤ (\u00A4) : Prefix or suffix : No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If tripled, replaced by currency plural names, for example, "US dollar" or "US dollars" for America. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.

但是这个:

$cFormatter->setTextAttribute(NumberFormatter::NEGATIVE_PREFIX, "-¤");

只是打印“-¤123”,所以没有快乐。

编辑 3:我想我找到了答案,见下文。

最佳答案

我发现了一种稍微不那么棘手的方法来将 en_US 语言环境行为转变为我正在寻找的东西 - getPattern()/setPattern() 函数。

$cFormatter = new NumberFormatter('en_US', NumberFormatter::CURRENCY);
$sPattern = $cFormatter->getPattern(); // returns "¤#,##0.00;(¤#,##0.00)";

$sMyPattern = "¤#,##0.00;-¤#,##0.00";
$cFormatter->setPattern($sMyPattern);
$cFormatter->formatCurrency(-456, 'USD');  // returns -$456.00

关于php - 如何让 NumberFormatter 打印带减号的负货币值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1160860/

相关文章:

swift - 使用正确的百分号(即%)将百分比数字格式化为zh(简体中文)

swift - 如何在 Swift 3 中格式化小数

Javascript 结果需要在 php 中捕获到电子邮件

php - 我如何组合这些 sql 查询的结果?

javascript - 如何在 JSP 中获取特定区域设置的货币符号

ItemTemplate 中的 .Net String.Format 货币与数据绑定(bind)中的小计

php - WordPress mysql 查询也可获取特色图像

php - 合并 2 个不同的表而不重复值 PHP

SQL 货币格式

swift - 大量的 NumberFormatter 问题