After reading about comparing float numbers, I wrote the following comparison:
$profitMarginPercent = (($clientTotal - $vendorTotal)/$vendorTotal) * 100;
if(abs($clientTotal - $vendorTotal) > PHP_FLOAT_EPSILON) {
$profitMarginPercent = "+".round($profitMarginPercent, 2);
}
elseif(abs($clientTotal - $vendorTotal) < PHP_FLOAT_EPSILON) {
$profitMarginPercent = "-".round($profitMarginPercent, 2);
}
elseif(abs($clientTotal - $vendorTotal) == PHP_FLOAT_EPSILON) {
$profitMarginPercent = round($profitMarginPercent, 2);
}
I want to print, for example, -50% if $vendorTotal
is greater than $clientTotal
or +50% if the other way round.
This works but with some exceptions:
-
If
$clientTotal
is 0.00000 and$vendorTotal
is any positive number, e.g. 14.72, my code prints+-100
. -
If the two variables are equal, e.g. 89.64110, my code prints
-0
.
Can you explain why this is happening and how I can fix it?
2
Answers
Here is a solution based on
sprintf()
:Output:
Small values are considered equal to zero.
I would go with something like this:
and then most likely put it in a function or method.
See: https://3v4l.org/j5BR7
What does it do?
As you can see I add
PHP_FLOAT_EPSILON
to the numerator of the division, this is to prevent a negative result when the numerator and denominator have the same value. It’s a very small value, and you round to two decimals, so it never changes the outcome.Then it adds a
+
character in front of the number whenever$profitMarginPercent
is positive. The-
character is already there when the value is negative.