Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP compare floats and print +/- before difference prints both + and –

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. If $clientTotal is 0.00000 and $vendorTotal is any positive number, e.g. 14.72, my code prints +-100.

  2. 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?

>Solution :

I would go with something like this:

$profitMarginPercent = round((($clientTotal - $vendorTotal + PHP_FLOAT_EPSILON)/$vendorTotal) * 100, 2);
$profitMarginPercent = ($profitMarginPercent > 0.0 ? "+" : "") . $profitMarginPercent;

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading