簡體   English   中英

PHP NumberFormatter 刪除.00

[英]PHP NumberFormatter removing the .00

嘗試從使用 PHP NumberFormatter 格式化的貨幣中刪除 last.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

我會做一個 str_replace for.00 但這可能因語言環境而異,所以看起來並不那么容易。

您只能使用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);

試試這個 :

$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";

如果您只想刪除.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');

如果您分別需要較低和較高的值,您也可以使用floorceil而不是 round。

<?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 $

在我看來, MIN_FRACTION_DIGITS 屬性將允許您像這樣抑制不需要的零:

$nf = new \NumberFormatter('en_US', \NumberFormatter::CURRENCY);
$nf->setAttribute( \NumberFormatter::MIN_FRACTION_DIGITS, 0 );
$nf->formatCurrency(0, 'EUR');

你不能用round()來做嗎?

echo round($nf, 0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM