Calculating 50% of a value

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

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