PHP NumberFormatter and Currency, can't set precision

瘦欲@ 提交于 2019-12-04 16:24:11

问题


I want to set a precision of 0 when using the NumberFormatter PHP class (from Intl extension) with currency. However I've got some strange result. Here:

$numberFormatter = new NumberFormatter('en-US', NumberFormatter::CURRENCY);
$numberFormatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);

echo $numberFormatter->formatCurrency('45', 'USD');

It outputs $45, which is what I want. However, if I change the currency to EUR with the same settings:

echo $numberFormatter->formatCurrency('45', 'EUR');

It outputs €45.00 (although I explicitly set to have a precision of zero).

Even more strange, if I set the locale to fr-FR, it outputs the number as expected:

$numberFormatter = new NumberFormatter('fr-FR', NumberFormatter::CURRENCY);
$numberFormatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 0);

echo $numberFormatter->formatCurrency('45', 'EUR');

It outputs 45 €.

Is this a bug?


回答1:


Michael Gallego forgot to update this issue. Check out his bug report and the replies at php.net.

  • https://bugs.php.net/bug.php?id=63140
  • http://bugs.icu-project.org/trac/ticket/7667

[2012-10-05 08:21 UTC] jpauli@email.com

I confirm this is an ICU bug in 4.4.x branch.
Consider upgrading libicu, 4.8.x gives correct result




回答2:


This function uses locale information to format number into currency, format I am are using is '%#10n' for $ :

/**
 * That it is an implementation of the function money_format for the
 * platforms that do not it bear.
 * The function accepts to same string of format accepts for the
 * original function of the PHP.
 * The function is tested using PHP 5.1.4 in Windows XP
 * and Apache WebServer.
 * 
 * format I am are using is '%#10n' for $;
 * 
*/
public static function money_format( $format, $number )
{
    $regex  = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
            '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
    if (setlocale(LC_MONETARY, 0) == 'C') {
        setlocale(LC_MONETARY, '');
    }
    $locale = localeconv();
    preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
    foreach ($matches as $fmatch) {
        $value = floatval($number);
        $flags = array(
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ?
                $match[1] : ' ',
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
                $match[0] : '+',
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
        );
        $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
        $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
        $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
        $conversion = $fmatch[5];

        $positive = true;
        if ($value < 0) {
            $positive = false;
            $value  *= -1;
        }
        $letter = $positive ? 'p' : 'n';

        $prefix = $suffix = $cprefix = $csuffix = $signal = '';

        $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
        switch (true) {
            case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
                $prefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
                $suffix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
                $cprefix = $signal;
                break;
            case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
                $csuffix = $signal;
                break;
            case $flags['usesignal'] == '(':
            case $locale["{$letter}_sign_posn"] == 0:
                $prefix = '(';
                $suffix = ')';
                break;
        }
        if (!$flags['nosimbol']) {
            $currency = $cprefix .
            ($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
            $csuffix;
        } else {
            $currency = '';
        }
        $space  = $locale["{$letter}_sep_by_space"] ? ' ' : '';

        $value = number_format($value, $right, $locale['mon_decimal_point'],
                $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
        $value = @explode($locale['mon_decimal_point'], $value);

        $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
        if ($left > 0 && $left > $n) {
            $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
        }
        $value = implode($locale['mon_decimal_point'], $value);
        if ($locale["{$letter}_cs_precedes"]) {
            $value = $prefix . $currency . $space . $value . $suffix;
        } else {
            $value = $prefix . $value . $space . $currency . $suffix;
        }
        if ($width > 0) {
            $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
                    STR_PAD_RIGHT : STR_PAD_LEFT);
        }

        $format = str_replace($fmatch[0], $value, $format);
    }
    return $format;
}



回答3:


You must provide a locale AND currency combination that is correct. For example, fr-FR / fr-bh / fr-ch support €, which is what must be provided in the formatCurrency function.




回答4:


I think you have to use a locale which supports the destination currency. So en_US don't have the Euro. de_DE have it and fr_FR also. So it is not strange that fr_FR supports Euro.

It seems that this is not a bug.




回答5:


Set the default locale value in the php ini you can use:

ini_set('intl.default_locale', 'de-DE');

To change the number format use:

setlocale(LC_MONETARY, 'de-DE');




回答6:


You can us the following line of code for formatting the money:-

$number = 1234.56;
setlocale(LC_MONETARY,"en_US"); // Sets the Default for money
echo money_format("%i", $number);

It will output you:

USD 1,234.56


来源:https://stackoverflow.com/questions/12339264/php-numberformatter-and-currency-cant-set-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!