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 be truncated to 0.76
So that he can feed the rest of the calculations, follow these steps:
4a. (( 0.76 * 30) + 8) / 40 = 0.77
And not for filing when rounding to two decimal places like 0.77 :
4b. (( 0.77 * 30) + 8) / 40 = 0.77
**** This seems to have failed and instead rounds to 0.77: ****
PHP function sptrinf (): PHP discards decimals without rounding
PHP function number_format (): PHP: displays a number up to two decimal places
PHP function floor (): Trim floating-point numbers with PHP
- Is there another way?
- Is it possible to achieve what I want (truncate to two decimal places) using PHP?
Help. Many thanks.
UPDATE - SOLVED
Okay, now it works thanks to dkamins and zneak. I used the floor () approach (I assume that in the past I did not do something like that). However, now the following happens:
eg.
(0.86 * 30) + 9) / 40 = 0.87 (he should), but after TRUNC it = 0.86
How does he trim 0.87 to 0.86? That doesn't make any sense. Is there a way to truncate it if there are more than two decimal places?
SOLVE:
$numDecPlace = strlen(substr(strrchr($newRel, "."), 1));
echo '<p>Test: Number of decimal places=' .$numDecPlace. '</p>';
if($numDecPlace > 2) {
$newRel = floor($newRel * 100) / 100;
echo '<p>Test: New relationship truncated is $newRel=' .$newRel. '</p>';
}
source
share