I have an algorithm that performs the following calculations:
- ( ( 0.50 * 0 ) + 7 ) / 10 = 0.70
- ( ( 0.70 * 10 ) + 9 ) / 20 = 0.80
- ( ( 0.80 * 20 ) + 7 ) / 30 = 0.7666666667 -> I want this value to truncate to 0.76
So that it may feed into the rest of the calculation as:
4a. ( ( 0.76 * 30 ) + 8 ) / 40 = 0.77
And not to feed in when rounded up two decimal places as 0.77:
4b. ( ( 0.77 * 30 ) + 8 ) / 40 = 0.77
The following seem to have failed and instead force a round up to 0.77:
The PHP sptrinf() function: PHP dropping decimals without rounding up
The PHP number_format() function: Show a number to two decimal places
The PHP floor() function: Truncate float numbers with PHP
- Is there another way?
- Is it at all possible to achieve what I want (truncate to two decimal places) with PHP?
UPDATE – SOLVED
Ok, it is working now thanks to dkamins and zneak. I used the floor() approach (I assume I wasn’t doing something right in the past). However, now the following happens:
e.g.
(0.86 * 30) + 9 ) / 40 = 0.87 (it should), yet after TRUNC it = 0.86
How is it truncating 0.87 to 0.86? It makes no sense. Is there a way to get it to truncate only if there are more than 2 decimal places?
You can use PHP’s floor function along with some decimal shifting like so: