In one of my wordpress theme function, this code is being used to calculate total billable amount: ceil(($cost * (1 + ($charges / 100))) * 100);
There is a little miscalculation happening for below scenario.
Scenario:
$charges = 9;
$cost = 100;
echo ceil(($cost * (1 + ($charges / 100))) * 100);
The above code outputs 10901 whereas it should be 10900.
It works fine for other scenarios like:
$charges = 4;
$cost = 90.7;
echo ceil(($cost * (1 + ($charges / 100))) * 100);
//outputs 9433, which is fine because manual calculation results 9432.8
Question:
- Why is that happening?
- How can I prevent that?
- Any alternate function to round to next nearest integer? (only if amount is floating value)
ceil($cost*(100+$charge));, see here: rextester.com/QQEYOS31143100 * (1 + (9 / 100))comes out as109.00000000000001. This is whyceil()appears to be rounding up. Please read both posts I've linked at the top of your questionround($cost*(100+$charge),6)to round to the closest number with 6 digits after the decimal point before using yourceil()function. However,round()is reported to be buggy in some cases. Otherwise you can also do a detour by creating a rounded string, likesprintf('%0.6f',$cost*(100+$charge))and then continue to do math with it (it will implicitly be converted back to float). In both cases theceil()function will be applied afterwards to turn the values into "the next larger integer".