我正在使用 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/