Alternative to money_format() function

Viewed 73043

I am trying to use the money_format() function in PHP, but it gives the following error:

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 strfmon capabilities (for example, Windows does not) and also that the function has been removed from PHP 8.0.

Is there an equivalent PHP function available?

15 Answers

As of php 8.0 money_format() has been removed. Checkout here

money_format() php function can only be used for php 7.4 and below. Alternatively you can use

numfmt_format_currency ( NumberFormatter $fmt , float $value , string $currency ) Read more from here

where:

fmt

NumberFormatter object.

value

The numeric currency value.

currency

The 3-letter ISO 4217 currency code indicating the currency to use.

Example:

$fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY );
echo numfmt_format_currency($fmt, 1234567.891234567890000, "EUR")."\n";

You can also use a very simple and straight forward laravel package: money-formatter

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

C:\XAMPP\php\php.ini

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

auto_prepend_file = "C:\money_format.php"

use this function in 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 
             '\=([\w\040])'.   // 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; 
} 

This PHP function will give you output based on INR formatting, pass the parameter, and you are done.

    function numberToCurrency($number){
        $checkMinusVal = explode('-',$number)[0];
        $checkMinus = $final = '';
        $allStr = explode('.',$number);
        if($checkMinusVal == ''){
            $checkMinus = '-';
            $allStr = explode('.',explode('-',$number)[1]);
        }
        $str = $allStr[0];
        $length = strlen($str);
        $count = $first = 0;
        for($i = $length; $i >= 0; $i--){   
            if($count == 3 && $first == 0){
                $final .= $str[$i];
                if($str[$i + 1] != ''){
                    $final .= ',';
                }
                $count = 0;
                $first = 1;
            }
            elseif($count == 2 && $first == 1){
                if( ($i - 1) < 0){
                    $final .= $str[$i];
                }
                else{
                    $final .= $str[$i].',';
                }
                $count = 0;
            }
            else{
                $final .= $str[$i];
            } 
            $count++;
        }
        $final = strrev($final);
        if(array_key_exists("1",$allStr)){
            $decimalVal = $allStr[1][0];
            if(!empty($allStr[1][1])){
                $decimalVal .= $allStr[1][1];
            }
            else{
                $decimalVal .= 0;
            }
            if($allStr[1][2] >= 5){
                $decimalVal++;
            }
            $final .= '.'.$decimalVal;
        }
        return $checkMinus.'₹'.$final.'/-';
    }

In your page call numberToCurrency($number) function and it will format and give you output in INR formatting only.

Sample Output:-

echo numberToCurrency('123') => ₹123/-

echo numberToCurrency('1234') => ₹1,234/-

echo numberToCurrency('1234567') => ₹12,34,567/-

echo numberToCurrency('1234567.123') => ₹12,34,567.12/-

echo numberToCurrency('1234567.125') => ₹12,34,567.13/-

echo numberToCurrency('-1234567.125') => -₹12,34,567.13/-

Related