Windows 平台上 PHP 中 money_format() 函数的替代方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6369887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:09:44  来源:igfitidea点击:

Alternative to money_format() Function in PHP on Windows Platform

phpwindowsmoney-format

提问by Pramod Kumar Sharma

I am using the money_format()function in PHP, which gives the following error:

money_format()在 PHP 中使用该函数,它给出了以下错误:

Fatal error: Call to undefined function money_format()

Searches about this error reveal that the function money_format()is only defined if the system has strfmoncapabilities. For example, Windows does not, so money_format()is undefined in Windows.

对此错误的搜索表明该函数money_format()仅在系统具有strfmon功能时才定义。例如,Windows 没有,因此money_format()在 Windows 中是 undefined。

Is there an equivalent PHP function available for Windows?

是否有可用于 Windows 的等效 PHP 函数?

采纳答案by Gordon

If you have the Intl extension, you can use

如果您有Intl 扩展名,则可以使用

Example from Manual

手册中的示例

$fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";
$fmt = new NumberFormatter( 'ru_RU', NumberFormatter::CURRENCY );
echo $fmt->formatCurrency(1234567.891234567890000, "EUR")."\n";
echo $fmt->formatCurrency(1234567.891234567890000, "RUR")."\n";

Output

输出

1.234.567,89 
1.234.567,89 RUR
1 234 567,89
1 234 567,89р.

Also see my answer on how to parse that formatted money string back into a float:

另请参阅我关于如何将格式化的货币字符串解析回浮点数的答案:

回答by tfont

Keep it simple!

把事情简单化!

sprintf('%01.2f', $val);

回答by Ajeet

<?php
function toMoney($val,$symbol='$',$r=2)
{


    $n = $val; 
    $c = is_float($n) ? 1 : number_format($n,$r);
    $d = '.';
    $t = ',';
    $sign = ($n < 0) ? '-' : '';
    $i = $n=number_format(abs($n),$r); 
    $j = (($j = $i.length) > 3) ? $j % 3 : 0; 

   return  $symbol.$sign .($j ? substr($i,0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"" + $t,substr($i,$j)) ;

}

echo toMoney(9856478521456.256);
?>

try this the out put of above code is "$9,856,478,521,456.26"

试试这个,上面代码的输出是“$9,856,478,521,456.26”

回答by Travis

I would suggest taking a look into NumberFormatterusing NumberFormatter::CURRENCYand locale.

我建议考虑NumberFormatter使用NumberFormatter::CURRENCY和语言环境。

Also Laravel number_format($price, 2)function is super useful.

Laravelnumber_format($price, 2)功能也非常有用。

Note, also useful functional that seems to contain similar format:

请注意,似乎也包含类似格式的有用功能:

function money_format($floatcurr, $curr = 'EUR')
{
    $currencies['ARS'] = array(2, ',', '.');          //  Argentine Peso
    $currencies['AMD'] = array(2, '.', ',');          //  Armenian Dram
    $currencies['AWG'] = array(2, '.', ',');          //  Aruban Guilder
    $currencies['AUD'] = array(2, '.', ' ');          //  Australian Dollar
    $currencies['BSD'] = array(2, '.', ',');          //  Bahamian Dollar
    $currencies['BHD'] = array(3, '.', ',');          //  Bahraini Dinar
    $currencies['BDT'] = array(2, '.', ',');          //  Bangladesh, Taka
    $currencies['BZD'] = array(2, '.', ',');          //  Belize Dollar
    $currencies['BMD'] = array(2, '.', ',');          //  Bermudian Dollar
    $currencies['BOB'] = array(2, '.', ',');          //  Bolivia, Boliviano
    $currencies['BAM'] = array(2, '.', ',');          //  Bosnia and Herzegovina, Convertible Marks
    $currencies['BWP'] = array(2, '.', ',');          //  Botswana, Pula
    $currencies['BRL'] = array(2, ',', '.');          //  Brazilian Real
    $currencies['BND'] = array(2, '.', ',');          //  Brunei Dollar
    $currencies['CAD'] = array(2, '.', ',');          //  Canadian Dollar
    $currencies['KYD'] = array(2, '.', ',');          //  Cayman Islands Dollar
    $currencies['CLP'] = array(0,  '', '.');          //  Chilean Peso
    $currencies['CNY'] = array(2, '.', ',');          //  China Yuan Renminbi
    $currencies['COP'] = array(2, ',', '.');          //  Colombian Peso
    $currencies['CRC'] = array(2, ',', '.');          //  Costa Rican Colon
    $currencies['HRK'] = array(2, ',', '.');          //  Croatian Kuna
    $currencies['CUC'] = array(2, '.', ',');          //  Cuban Convertible Peso
    $currencies['CUP'] = array(2, '.', ',');          //  Cuban Peso
    $currencies['CYP'] = array(2, '.', ',');          //  Cyprus Pound
    $currencies['CZK'] = array(2, '.', ',');          //  Czech Koruna
    $currencies['DKK'] = array(2, ',', '.');          //  Danish Krone
    $currencies['DOP'] = array(2, '.', ',');          //  Dominican Peso
    $currencies['XCD'] = array(2, '.', ',');          //  East Caribbean Dollar
    $currencies['EGP'] = array(2, '.', ',');          //  Egyptian Pound
    $currencies['SVC'] = array(2, '.', ',');          //  El Salvador Colon
    $currencies['ATS'] = array(2, ',', '.');          //  Euro
    $currencies['BEF'] = array(2, ',', '.');          //  Euro
    $currencies['DEM'] = array(2, ',', '.');          //  Euro
    $currencies['EEK'] = array(2, ',', '.');          //  Euro
    $currencies['ESP'] = array(2, ',', '.');          //  Euro
    $currencies['EUR'] = array(2, ',', '.');          //  Euro
    $currencies['FIM'] = array(2, ',', '.');          //  Euro
    $currencies['FRF'] = array(2, ',', '.');          //  Euro
    $currencies['GRD'] = array(2, ',', '.');          //  Euro
    $currencies['IEP'] = array(2, ',', '.');          //  Euro
    $currencies['ITL'] = array(2, ',', '.');          //  Euro
    $currencies['LUF'] = array(2, ',', '.');          //  Euro
    $currencies['NLG'] = array(2, ',', '.');          //  Euro
    $currencies['PTE'] = array(2, ',', '.');          //  Euro
    $currencies['GHC'] = array(2, '.', ',');          //  Ghana, Cedi
    $currencies['GIP'] = array(2, '.', ',');          //  Gibraltar Pound
    $currencies['GTQ'] = array(2, '.', ',');          //  Guatemala, Quetzal
    $currencies['HNL'] = array(2, '.', ',');          //  Honduras, Lempira
    $currencies['HKD'] = array(2, '.', ',');          //  Hong Kong Dollar
    $currencies['HUF'] = array(0,  '', '.');          //  Hungary, Forint
    $currencies['ISK'] = array(0,  '', '.');          //  Iceland Krona
    $currencies['INR'] = array(2, '.', ',');          //  Indian Rupee
    $currencies['IDR'] = array(2, ',', '.');          //  Indonesia, Rupiah
    $currencies['IRR'] = array(2, '.', ',');          //  Iranian Rial
    $currencies['JMD'] = array(2, '.', ',');          //  Jamaican Dollar
    $currencies['JPY'] = array(0,  '', ',');          //  Japan, Yen
    $currencies['JOD'] = array(3, '.', ',');          //  Jordanian Dinar
    $currencies['KES'] = array(2, '.', ',');          //  Kenyan Shilling
    $currencies['KWD'] = array(3, '.', ',');          //  Kuwaiti Dinar
    $currencies['LVL'] = array(2, '.', ',');          //  Latvian Lats
    $currencies['LBP'] = array(0,  '', ' ');          //  Lebanese Pound
    $currencies['LTL'] = array(2, ',', ' ');          //  Lithuanian Litas
    $currencies['MKD'] = array(2, '.', ',');          //  Macedonia, Denar
    $currencies['MYR'] = array(2, '.', ',');          //  Malaysian Ringgit
    $currencies['MTL'] = array(2, '.', ',');          //  Maltese Lira
    $currencies['MUR'] = array(0,  '', ',');          //  Mauritius Rupee
    $currencies['MXN'] = array(2, '.', ',');          //  Mexican Peso
    $currencies['MZM'] = array(2, ',', '.');          //  Mozambique Metical
    $currencies['NPR'] = array(2, '.', ',');          //  Nepalese Rupee
    $currencies['ANG'] = array(2, '.', ',');          //  Netherlands Antillian Guilder
    $currencies['ILS'] = array(2, '.', ',');          //  New Israeli Shekel
    $currencies['TRY'] = array(2, '.', ',');          //  New Turkish Lira
    $currencies['NZD'] = array(2, '.', ',');          //  New Zealand Dollar
    $currencies['NOK'] = array(2, ',', '.');          //  Norwegian Krone
    $currencies['PKR'] = array(2, '.', ',');          //  Pakistan Rupee
    $currencies['PEN'] = array(2, '.', ',');          //  Peru, Nuevo Sol
    $currencies['UYU'] = array(2, ',', '.');          //  Peso Uruguayo
    $currencies['PHP'] = array(2, '.', ',');          //  Philippine Peso
    $currencies['PLN'] = array(2, '.', ' ');          //  Poland, Zloty
    $currencies['GBP'] = array(2, '.', ',');          //  Pound Sterling
    $currencies['OMR'] = array(3, '.', ',');          //  Rial Omani
    $currencies['RON'] = array(2, ',', '.');          //  Romania, New Leu
    $currencies['ROL'] = array(2, ',', '.');          //  Romania, Old Leu
    $currencies['RUB'] = array(2, ',', '.');          //  Russian Ruble
    $currencies['SAR'] = array(2, '.', ',');          //  Saudi Riyal
    $currencies['SGD'] = array(2, '.', ',');          //  Singapore Dollar
    $currencies['SKK'] = array(2, ',', ' ');          //  Slovak Koruna
    $currencies['SIT'] = array(2, ',', '.');          //  Slovenia, Tolar
    $currencies['ZAR'] = array(2, '.', ' ');          //  South Africa, Rand
    $currencies['KRW'] = array(0,  '', ',');          //  South Korea, Won
    $currencies['SZL'] = array(2, '.', ', ');         //  Swaziland, Lilangeni
    $currencies['SEK'] = array(2, ',', '.');          //  Swedish Krona
    $currencies['CHF'] = array(2, '.', '\'');         //  Swiss Franc
    $currencies['TZS'] = array(2, '.', ',');          //  Tanzanian Shilling
    $currencies['THB'] = array(2, '.', ',');          //  Thailand, Baht
    $currencies['TOP'] = array(2, '.', ',');          //  Tonga, Paanga
    $currencies['AED'] = array(2, '.', ',');          //  UAE Dirham
    $currencies['UAH'] = array(2, ',', ' ');          //  Ukraine, Hryvnia
    $currencies['USD'] = array(2, '.', ',');          //  US Dollar
    $currencies['VUV'] = array(0,  '', ',');          //  Vanuatu, Vatu
    $currencies['VEF'] = array(2, ',', '.');          //  Venezuela Bolivares Fuertes
    $currencies['VEB'] = array(2, ',', '.');          //  Venezuela, Bolivar
    $currencies['VND'] = array(0,  '', '.');          //  Viet Nam, Dong
    $currencies['ZWD'] = array(2, '.', ' ');          //  Zimbabwe Dollar
    // custom function to generate: ##,##,###.##
    function formatinr($input)
    {
        $dec = "";
        $pos = strpos($input, ".");
        if ($pos === FALSE)
        {
            //no decimals
        }
        else
        {
            //decimals
            $dec   = substr(round(substr($input, $pos), 2), 1);
            $input = substr($input, 0, $pos);
        }
        $num   = substr($input, -3);    // get the last 3 digits
        $input = substr($input, 0, -3); // omit the last 3 digits already stored in $num
        // loop the process - further get digits 2 by 2
        while (strlen($input) > 0)
        {
            $num   = substr($input, -2).",".$num;
            $input = substr($input, 0, -2);
        }
        return $num.$dec;
    }
    if ($curr == "INR")
    {
        return formatinr($floatcurr);
    }
    else
    {
        return number_format($floatcurr, $currencies[$curr][0], $currencies[$curr][1], $currencies[$curr][2]);
    }
}

And don't forget to check if the function exist!

并且不要忘记检查该函数是否存在!

if (!function_exists('money_format')) { //... }

回答by Brian Powell

I always just used this to manually add the dollar sign:

我总是用它来手动添加美元符号:

// for $k = 53.234234978
$k = "$ " . number_format($k, 2);
// output = $ 53.23

回答by nageen nayak

The solution to this problem is create a PHP file with the money_format() function and use the Apache auto_prepend_file directive in your php.ini file. Usually, if you use XAMPP, your php.ini should be in

此问题的解决方案是使用 money_format() 函数创建一个 PHP 文件,并在 php.ini 文件中使用 Apache auto_prepend_file 指令。通常,如果你使用 XAMPP,你的 php.ini 应该在

C:\XAMPP\php\php.ini

Append this line of code to your php.ini file.

将这行代码附​​加到您的 php.ini 文件中。

auto_prepend_file = "C:\money_format.php"

use this function in money_format.php

使用这个功能 money_format.php

function money_format($formato, $valor) { 


    if (setlocale(LC_MONETARY, 0) == 'C') { 
        return number_format($valor, 2); 
    }

    $locale = localeconv(); 

    $regex = '/^'.             // Inicio da Expressao 
             '%'.              // Caractere % 
             '(?:'.            // Inicio das Flags opcionais 
             '\=([\w0])'.   // Flag =f 
             '|'. 
             '([\^])'.         // Flag ^ 
             '|'. 
             '(\+|\()'.        // Flag + ou ( 
             '|'. 
             '(!)'.            // Flag ! 
             '|'. 
             '(-)'.            // Flag - 
             ')*'.             // Fim das flags opcionais 
             '(?:([\d]+)?)'.   // W  Largura de campos 
             '(?:#([\d]+))?'.  // #n Precisao esquerda 
             '(?:\.([\d]+))?'. // .p Precisao direita 
             '([in%])'.        // Caractere de conversao 
             '$/';             // Fim da Expressao 

    if (!preg_match($regex, $formato, $matches)) { 
        trigger_error('Formato invalido: '.$formato, E_USER_WARNING); 
        return $valor; 
    } 

    $opcoes = array( 
        'preenchimento'   => ($matches[1] !== '') ? $matches[1] : ' ', 
        'nao_agrupar'     => ($matches[2] == '^'), 
        'usar_sinal'      => ($matches[3] == '+'), 
        'usar_parenteses' => ($matches[3] == '('), 
        'ignorar_simbolo' => ($matches[4] == '!'), 
        'alinhamento_esq' => ($matches[5] == '-'), 
        'largura_campo'   => ($matches[6] !== '') ? (int)$matches[6] : 0, 
        'precisao_esq'    => ($matches[7] !== '') ? (int)$matches[7] : false, 
        'precisao_dir'    => ($matches[8] !== '') ? (int)$matches[8] : $locale['int_frac_digits'], 
        'conversao'       => $matches[9] 
    ); 

    if ($opcoes['usar_sinal'] && $locale['n_sign_posn'] == 0) { 
        $locale['n_sign_posn'] = 1; 
    } elseif ($opcoes['usar_parenteses']) { 
        $locale['n_sign_posn'] = 0; 
    } 
    if ($opcoes['precisao_dir']) { 
        $locale['frac_digits'] = $opcoes['precisao_dir']; 
    } 
    if ($opcoes['nao_agrupar']) { 
        $locale['mon_thousands_sep'] = ''; 
    } 

    $tipo_sinal = $valor >= 0 ? 'p' : 'n'; 
    if ($opcoes['ignorar_simbolo']) { 
        $simbolo = ''; 
    } else { 
        $simbolo = $opcoes['conversao'] == 'n' ? $locale['currency_symbol'] 
                                               : $locale['int_curr_symbol']; 
    } 
    $numero = number_format(abs($valor), $locale['frac_digits'], $locale['mon_decimal_point'], $locale['mon_thousands_sep']); 


    $sinal = $valor >= 0 ? $locale['positive_sign'] : $locale['negative_sign']; 
    $simbolo_antes = $locale[$tipo_sinal.'_cs_precedes']; 

    $espaco1 = $locale[$tipo_sinal.'_sep_by_space'] == 1 ? ' ' : ''; 

    $espaco2 = $locale[$tipo_sinal.'_sep_by_space'] == 2 ? ' ' : ''; 

    $formatado = ''; 
    switch ($locale[$tipo_sinal.'_sign_posn']) { 
    case 0: 
        if ($simbolo_antes) { 
            $formatado = '('.$simbolo.$espaco1.$numero.')'; 
        } else { 
            $formatado = '('.$numero.$espaco1.$simbolo.')'; 
        } 
        break; 
    case 1: 
        if ($simbolo_antes) { 
            $formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero; 
        } else { 
            $formatado = $sinal.$numero.$espaco1.$simbolo; 
        } 
        break; 
    case 2: 
        if ($simbolo_antes) { 
            $formatado = $simbolo.$espaco1.$numero.$sinal; 
        } else { 
            $formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal; 
        } 
        break; 
    case 3: 
        if ($simbolo_antes) { 
            $formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero; 
        } else { 
            $formatado = $numero.$espaco1.$sinal.$espaco2.$simbolo; 
        } 
        break; 
    case 4: 
        if ($simbolo_antes) { 
            $formatado = $simbolo.$espaco2.$sinal.$espaco1.$numero; 
        } else { 
            $formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal; 
        } 
        break; 
    } 

    if ($opcoes['largura_campo'] > 0 && strlen($formatado) < $opcoes['largura_campo']) { 
        $alinhamento = $opcoes['alinhamento_esq'] ? STR_PAD_RIGHT : STR_PAD_LEFT; 
        $formatado = str_pad($formatado, $opcoes['largura_campo'], $opcoes['preenchimento'], $alinhamento); 
    } 

    return $formatado; 
} 

回答by user3860170

 function toMoney($val,$symbol='$',$r=2)
{


    $n = $val; 
    $c = is_float($n) ? 1 : number_format($n,$r);
    $d = '.';
    $t = ',';
    $sign = ($n < 0) ? '-' : '';
    $i = $n=number_format(abs($n),$r); 
    $j = (($j = strlen($i)) > 3) ? $j % 3 : 0; 

   return  $symbol.$sign .($j ? substr($i,0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"" + $t,substr($i,$j)) ;

}

echo toMoney(45); ; 

output:$45.00

输出:$45.00

回答by Sachith

Instead of money_format()you can also try this. Hope this will be helped any guy who faced this call to undefined function money_format()error.

而不是money_format()你也可以试试这个。希望这会对任何遇到此call to undefined function money_format()错误的人有所帮助。

<?php
    $price = number_format($price, 2); 
    echo "$".$price;
?>

Output:

输出:

0.00

回答by ling

I use this function:

我使用这个功能:

function formatPrice($number, array $options = [])
{
    $options = array_replace([
        'alwaysShowDecimals' => true,
        'nbDecimals' => 2,
        'decPoint' => ".",
        'thousandSep' => "",
        'moneySymbol' => "",
        'moneyFormat' => "vs", // v represents the value, s represents the money symbol
    ], $options);
    extract($options);

    $v = number_format($number, $nbDecimals, $decPoint, $thousandSep);
    if (false === $alwaysShowDecimals && $nbDecimals > 0) {
        $p = explode($decPoint, $v);
        $dec = array_pop($p);
        if (0 === (int)$dec) {
            $v = implode('', $p);
        }
    }
    $ret = str_replace([
        'v',
        's',
    ], [
        $v,
        $moneySymbol,
    ], $moneyFormat);
    return $ret;

}

And use it like this:

并像这样使用它:

$numbers = [
    1500,
    90,
    17.52,
    3650.95,
];

$options = [
    'alwaysShowDecimals' => true,
    'nbDecimals' => 2,
    'decPoint' => ".",
    'thousandSep' => "",
    'moneySymbol' => "",
    'moneyFormat' => "vs", // v represents the value, s represents the money symbol
];
foreach ($numbers as $number) {
    echo formatPrice($number, $options);
    echo "<br>";
}
/**
 * output:
 * 
 * 1500.00
 * 90.00
 * 17.52
 * 3650.95
 * 
 */

回答by Don Gabo

**

**

CLP money (moneda peso chileno, con formato miles)

CLP 钱 (moneda peso chileno, con formato 英里)

**

**

    function toMoney($val,$symbol='$',$r=0)
{
    $n = $val; 
    $c = is_float($n) ? 1 : number_format($n,$r);
    $d = '.';
    $t = ',';
    $sign = ($n < 0) ? '-' : '';
    $i = $n=number_format(abs($n),$r); 
    $j = (($j = strlen($i)) > 2) ? $j % 2 : 0; 

   return  $symbol.$sign .($j ? substr($i,0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"" + $t,substr($i,$j)) ;

}

echo toMoney(45); 
echo toMoney(4500);  ,500
echo toMoney(45000);  ,000