I'm hoping someone can see where I'm going wrong.
I have 3 pricing values projectBudget
, projectOverflow
, projectTotal
, and what I'm trying to do is to create
a check that will set a variable to true or false.
So if my projectTotal
is greater then the projectBudget
but less then projectOverflow
I need to set my projectWarning
variable to true
but if my projectTotal
is greater then projectBudget
and it's greater then projectOverflow
I then need to set my projectDanger
variable to true and my projectWarning
to false.
The issue I'm having is that my projectWarning
is true and my projectDanger
is false even though my projectTotal
is greater then
projectBudget
and projectOverflow
Here is my code
$projectBudget = number_format((float)$project->budget, 2) // 1
$projectOverflow = number_format((float)$project->overflow, 2) // 2
$projectTotal = number_format((float)$project->total, 2) // 1234
$projectWarning = false;
$projectDanger = false;
if($projectTotal > $projectBudget && $projectTotal < $projectOverflow)
{
$projectWarning = true;
}
if($projectTotal > $projectOverflow)
{
$projectDanger = true;
}
dd($projectWarning , $projectDanger);
CodePudding user response:
Let's make a Minimal, Reproducible Example with just the first part of your code:
$project = new class {
public $budget = 1;
public $overflow = 2;
public $total = 1234;
};
$projectBudget = number_format((float)$project->budget, 2); // 1
$projectOverflow = number_format((float)$project->overflow, 2); // 2
$projectTotal = number_format((float)$project->total, 2); // 1234
var_dump($projectBudget, $projectOverflow, $projectTotal);
If you look at the var_dump output, you'll see that the comments of the different variables are wrong - because you've called number_format
, the variables now hold strings, "1.00", "2.00", and "1,234.00".
So now when you compare those variables, you're comparing strings, which will look at which one comes first in alphabetical order - clearly not what you intended.
The fix is simple: don't format numbers until you're actually presenting them to a user.
CodePudding user response:
Just remove number_format
from your code.
Comparative operators do not work with it.