簡體   English   中英

PHP NumberFormatter和Currency,無法設置精度

[英]PHP NumberFormatter and Currency, can't set precision

我想在使用帶貨幣的NumberFormatter PHP類(來自Intl擴展名 )時設置精度為0。 但是我得到了一些奇怪的結果。 這里:

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

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

它輸出$45 ,這是我想要的。 但是,如果我使用相同的設置將貨幣更改為EUR

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

它輸出€45.00 (雖然我明確設置精度為零)。

更奇怪的是,如果我將語言環境設置為fr-FR ,它會按預期輸出數字:

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

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

它輸出45 €

這是一個錯誤嗎?

Michael Gallego忘了更新這個問題 查看他的錯誤報告和php.net上的回復。

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

我確認這是4.4.x分支中的ICU錯誤。
考慮升級libicu,4.8.x給出正確的結果

您必須提供正確的區域設置和貨幣組合。 例如,fr-FR / fr-bh / fr-ch支持€,這是formatCurrency函數中必須提供的。

此函數使用區域設置信息將數字格式化為貨幣,我正在使用的格式為'%#10n'為$:

/**
 * 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;
}

我認為你必須使用支持目標貨幣的區域設置。 所以en_US沒有歐元。 de_DE也有它和fr_FR。 所以fr_FR支持歐元並不奇怪。

看來這不是一個bug。

在您可以使用的php ini中設置默認語言環境值:

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

要更改數字格式,請使用:

setlocale(LC_MONETARY,'de-DE');

您可以使用以下代碼行格式化資金: -

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

它會輸出你:

USD 1,234.56

暫無
暫無

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

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