How to multiply $variable that includes € with a v

2019-09-17 09:09发布

since I'm new to PHP I have a quite simple question. After Googling and searching here on stackoverflow I still can't get it to work.

<?php 
    $payinfront = $product->get_price_html();
    $totalprice = $payinfront * 2;
?>

<p class="price">Total price: <?php echo $totalprice ?></p>
<p class="price">Amount to pay in front: <?php echo $payinfront ?></p>
<p class="price">Amount to pay after: <?php echo $totalprice - $payinfront ?></p>

The $payinfront value does get it's value from another part of my template. Let's say it's €10,-. This is the amount people have to pay in front. When we have done the service they have to pay the other half wich is the last rule.

Thanks for helping me out!

4条回答
倾城 Initia
2楼-- · 2019-09-17 09:15

You want to store prices as floats, not as strings, so that PHP can recognize them as numeric values, and do calculations on them. Only cast them to strings at the very last moment, when you are echoing them in your template.

<?php
    $payInFront = $product->getPrice(); // should return a numeric value, instead of a string
    $totalPrice = $payInFront * 2;
    $payAfter   = $totalPrice - $payInFront;
?>

Then, when you echo the prices, you might want to format them in a certain way, using number_format():

<p>Price: &euro; <?php echo number_format($totalPrice, 2, ',', '.'); ?></p>
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-09-17 09:18

You first have to remove the euro sign so that the variable can be considered a number. Then you make the multiplication and concatenate the euro sign below at the html part.

<?php 
    $payinfront = $product->get_price_html();
    $payinfront = str_replace("&euro;","",$payinfront);
    $totalprice = $payinfront * 2;
?>

<p class="price">Total price: <?php echo $totalprice ?>&euro;</p>
<p class="price">Amount to pay in front: <?php echo $payinfront ?>&euro;</p>
<p class="price">Amount to pay after: <?php echo $totalprice - $payinfront ?>&euro;</p>
查看更多
SAY GOODBYE
4楼-- · 2019-09-17 09:27

Like this?

<?php 
    $payinfront = $product->get_price_html();
    $totalprice = $payinfront * 2;
?>

<p class="price">Total price: &euro;<?php echo $totalprice ?></p>
<p class="price">Amount to pay in front: &euro;<?php echo $payinfront ?></p>
<p class="price">Amount to pay after: &euro;<?php echo $totalprice - $payinfront ?></p>

Note that &euro; makes an euro sign

查看更多
不美不萌又怎样
5楼-- · 2019-09-17 09:28

Remove the currency symbol before multiplication:

$totalprice =  substr($payinfront, 1) * 2;
查看更多
登录 后发表回答