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