Fatal error: Call to undefined function money_format()

PhpCartShopping

Php Problem Overview


Every time I try to run this code there is a message saying:

Fatal error: Call to undefined function money_format()

The lines that have that problem are:

$pricetotal = money_format("%10.2n", $pricetotal);

and

$cartTotal = money_format("%10.2n", $cartTotal);

Can you please explain me the reason why this happens ?

$cartOutput = "";
$cartTotal = "";
$pp_checkout_btn = '';
$product_id_array = '';
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
    // Start PayPal Checkout Button
$pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    <input type="hidden" name="business" value="[email protected]">';
    // Start the For Each loop
    $i = 0; 
    foreach ($_SESSION["cart_array"] as $each_item) { 
	    $item_id = $each_item['item_id'];
	    $sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
	    while ($row = mysql_fetch_array($sql)) {
		    $product_name = $row["product_name"];
		    $price = $row["price"];
		    $details = $row["details"];
	    }
	    $pricetotal = $price * $each_item['quantity'];
	    $cartTotal = $pricetotal + $cartTotal;
	    setlocale(LC_MONETARY, "en_US");
        $pricetotal = money_format("%10.2n", $pricetotal);
	    // Dynamic Checkout Btn Assembly
	    $x = $i + 1;
	    $pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
        <input type="hidden" name="amount_' . $x . '" value="' . $price . '">
        <input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '">  ';
	    // Create the product array variable
	    $product_id_array .= "$item_id-".$each_item['quantity'].","; 
	    // Dynamic table row assembly
	    $cartOutput .= "<tr>";
	    $cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' .     $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>';
	$cartOutput .= '<td>' . $details . '</td>';
	$cartOutput .= '<td>$' . $price . '</td>';
	$cartOutput .= '<td><form action="cart.php" method="post">
	<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
	<input name="adjustBtn' . $item_id . '" type="submit" value="change" />
	<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
	</form></td>';
	//$cartOutput .= '<td>' . $each_item['quantity'] . '</td>';
	$cartOutput .= '<td>' . $pricetotal . '</td>';
	$cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>';
	$cartOutput .= '</tr>';
	$i++; 
} 
setlocale(LC_MONETARY, "en_US");
$cartTotal = money_format("%10.2n", $cartTotal);
$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." USD</div>";
// Finish the Paypal Checkout Btn
$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www.yoursite.com/storescripts/my_ipn.php">
<input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>';
}
?>

Php Solutions


Solution 1 - Php

if you are using windows based system then you will not have this function available.

The function money_format() is only defined if the system has strfmon capabilities. For example, Windows does not, so money_format() is undefined in Windows.

(this has been pointed out by Mike W in comments as well)

http://www.php.net/manual/en/function.money-format.php

Solution 2 - Php

It has been pointed out that you may not have this function because it does not exist on all operating systems (see Mike W's comment or Learner Student's answer).

Since the function appears absent on your system, you can write your own function based on the number_format function. You appear to want to format the number as US dollars, so the default (decimal = . and thousands = , should work for you).

function asDollars($value) {
  if ($value<0) return "-".asDollars(-$value);
  return '$' . number_format($value, 2);
}

Then you can replace

$pricetotal = money_format("%10.2n", $pricetotal);

with

$pricetotal = asDollars($pricetotal);

The updated code puts the negative sign in front of the currency sign even for negative numbers (per the comment by @kunal).

Solution 3 - Php

I had the same issue while developing a site on Laravel. For me, I replaced older code :

return money_format('$%i', $this->price / 100);

with the following:

return '$' . number_format(($this->price) / 100);

Solution 4 - Php

For Windows WAMP User and > PHP v7.4.2 please you might use this function which implements the same function for all platforms from here money_format()

Please use that function as fallback.. so use if ( ! function_exists( 'money_format' ) ) {} to avoid function can not redeclare fatal error.

Below for quick copying...

if ( ! function_exists( 'money_format' ) ) {

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

Solution 5 - Php

i am using a windows OS and I replaced;

return money_format('$%i', $this->price / 100);

with the following:

return '$' . number_format($this->price / 100, 2); //the '2' is for the decimal point.

Solution 6 - 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; 
} 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser3201312View Question on Stackoverflow
Solution 1 - PhpJason WView Answer on Stackoverflow
Solution 2 - PhpFlorisView Answer on Stackoverflow
Solution 3 - PhpPrem SagarView Answer on Stackoverflow
Solution 4 - PhpSajjad Hossain SagorView Answer on Stackoverflow
Solution 5 - PhpBenjamin AlenoghenaView Answer on Stackoverflow
Solution 6 - PhpPriyesh ShuklaView Answer on Stackoverflow