Calculating 50% of a value

3 posts by 2 authors in: Forums > CMS Builder
Last Post: February 13, 2019   (RSS)

By JeffC - February 13, 2019

Hi

I have an order form. The item price is displayed with:

<?php echo htmlEncode($item['price']); ?>

The price is payable in two equal instalments, and I would like to display the cost of each instalment.

The cost of each instalment is:

($item['price']) / 2

or

($item['price']) * 0.5

Is there a way to use php to perform the calculation?

Here's my complete code:

<strong><?php echo @htmlEncode($publications[$item['products.publicationsNum']]['title']); ?> - <?php echo htmlEncode($item['products.title']); ?></strong><br/>
<?php echo $item['products.product_description']; ?><br>
<strong>Total Cost: </strong>&pound;<?php echo htmlEncode($item['price']); ?><br/>
Payable in two instalments of [instalment cost goes here]. Invoiced in March and September.<br/>

Thanks

Jeff

By daniel - February 13, 2019

Hi Jeffncou,

Yes, PHP handles simple math operations fairly easily. Simply adding the math operation to the code will perform the calculation:

<?php echo htmlEncode($item['price'] * 0.5); ?>

One additional step you might want to take is to round the result so that you don't end up with more than two decimal places. That could look something like this (broken into two lines to help with readability):

<?php $halfPrice = round( $item['price'] * 0.5, 2 ); ?>
<?php echo htmlEncode($halfPrice); ?>

Documentation on the round() function: http://php.net/manual/en/function.round.php

Let me know if that does the trick!

Thanks,

Daniel
Technical Lead
interactivetools.com

By JeffC - February 13, 2019 - edited: February 13, 2019

Hi Daniel

Thanks for that solution.

With regards to the rounding to two decimal places, please could you advise how to force two decimals.

So that, for example, 101 * 0.5 results in 50.50 and not 50.5

Thanks

Edit: I've sussed it. I have replaced htmlEncode with number_format – seems to have done the trick!

<?php echo number_format($item['price'] * 0.5, 2); ?>

Thanks for getting me on the right road :)

Jeff