Jump to content

apply money_format to multiple values


phpnew

Recommended Posts

Hi,

I have a group of variables that are prices of different products. To simplify:

$price1 = "39.99";
$price2 = "35.99";
$price3 = "69.99";
$price4 = "89.99";

I have to set locale and apply money_format to all of these, so they are shown in a right currency when they get echoed on an HTML page.

Right now, I can do it like this:

<?php setlocale(LC_MONETARY,'de_DE');echo money_format("%n",$price3);?>

Is it possible to apply the money_format to the group of prices before i echo it on the page? If it is, then my final code for prices would look like:

<?php echo $price3;?>

In the above case, $price3 would already be formatted for de_DE currency.

Thank you

 

Link to comment
Share on other sites

Thanks.
I tried, but my coding did not work.

 

$prices = array(
$price1 = "39.99",
$price2 = "35.99",
$price3 = "69.99",
$price4 = "89.99
);

function setPrices($prices) {
setlocale(LC_MONETARY, "de_DE");
return money_format("%n", $prices);
}

I also tried echo instead of return inside the function.

With "return" I tried echo $price3 inside HTML, did not work.

With "echo" I tried setPrices($price1) inside HTML, but that did not work either.

No error, but would get prices as they entered, with dots for decimals, and no currency sign.

I also tried with starting the function like function setPrices()....

Thanks

 

P.S.

This actually works now, after I used the function name to call it from within HTML.

I did

echo setPrices($price3)


 

Thank you

Link to comment
Share on other sites

If you have

$price1 = "39.99";
$price2 = "35.99";
$price3 = "69.99";
$price4 = "89.99";

then why not

setlocale(LC_MONETARY, "de_DE"); // you really should expand this list to be cross-platform safe
$price1 = money_format("%n", 39.99);
$price2 = money_format("%n", 35.99);
$price3 = money_format("%n", 69.99);
$price4 = money_format("%n", 89.99);

 

How are your values getting into the variables in the first place?

Link to comment
Share on other sites

Alternative for Windows users with no money_format() function

$prices = [ 39.99, 35.99, 69.99, 89.99 ];

function deu_money($n)
{
    return '&euro;'.number_format($n, 2, ',', '.');
}

$prices = array_map( 'deu_money' , $prices);

giving

$prices Array
(
    [0] => €39,99
    [1] => €35,99
    [2] => €69,99
    [3] => €89,99
)

 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.