Alternative to money_format() Function in PHP on Windows Platform

前端 未结 13 1973
天命终不由人
天命终不由人 2020-12-01 09:02

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

Fatal error: Call to undefined function money_format()
         


        
13条回答
  •  臣服心动
    2020-12-01 09:47

    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 "
    "; } /** * output: * * 1500.00€ * 90.00€ * 17.52€ * 3650.95€ * */

提交回复
热议问题