尝试从使用PHP NumberFormatter格式化的货币中删除最后一个.00但似乎不可能。我可以看到此选项,但它似乎不会影响货币:DECIMAL_ALWAYS_SHOWN
$nf = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$nf->formatCurrency(0, 'EUR');
// Output is €0.00 but it doesn't seem possible to remove the .00
我会为.00做一个str_replace,但这可能会有所不同,具体取决于区域设置,所以看起来并不那么容易。
答案 0 :(得分:3)
您只能使用format()
方法强制执行此操作:
$nf = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$nf->setTextAttribute(\NumberFormatter::CURRENCY_CODE, 'EUR');
$nf->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, 0);
echo $nf->format(1);
答案 1 :(得分:1)
试试这个:
$nf = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$nf->formatCurrency(0, 'EUR');
numfmt_set_attribute($nf, \NumberFormatter::MAX_FRACTION_DIGITS, 0);
echo numfmt_format($nf, 123.00)."\n";
答案 2 :(得分:0)
如果您只想删除.00
,并希望保留.00
以外的其他内容,则可以尝试:
$formatter = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$money = $formatter->formatCurrency($money, 'USD');
$money = rtrim($money,".00");
如果您希望将所有这些数字四舍五入到小数点后,则可以添加round
:
$formatter = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$money = $formatter->formatCurrency(round($money,0), 'USD');
如果您分别需要较低和较高的值,也可以使用floor
和ceil
代替回合。
答案 3 :(得分:0)
<?php
declare(strict_types=1);
/**
* Format a float value into a formatted number with currency,
* depending on the locale and the currency code.
*/
function customCurrencyFormatter(float $value, ?string $locale = 'en_US', ?string $currencyCode = 'EUR'): string {
// Init number formatter and its default settings.
$nf = new \NumberFormatter($locale ?? Locale::getDefault(), \NumberFormatter::CURRENCY);
$nf->setTextAttribute(\NumberFormatter::CURRENCY_CODE, $currencyCode);
// Apply number rules. Here, we round it at the number of decimals
// we want to display on non-integer values.
// Examples.
// 2 decimals: 1.949 -> 1.95
// 3 decimals: 1.9485 -> 1.949
$value = \round($value, $nf->getAttribute(\NumberFormatter::MIN_FRACTION_DIGITS));
// Detect if the rounded result is an integer value.
// If so, remove decimals from the formatting.
if (\intval($value) == $value) {
$nf->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, 0);
}
// Convert non-breaking and narrow non-breaking spaces to normal ones.
return \str_replace(["\xc2\xa0", "\xe2\x80\xaf"], ' ', $nf->format($value));
}
echo customCurrencyFormatter(2.999, 'de_DE', 'USD') . \PHP_EOL;
// 3 $
echo customCurrencyFormatter(2.949, 'de_DE', 'USD') . \PHP_EOL;
// 2,95 $
答案 4 :(得分:-3)
echo round($nf, 0)