I have a simple calculation using php below, i want to get the sum of total displayed with '+' if the number is positive, eg. '+121', can it be done?
$total = $row["subtotal1"] - $row["subtotal2"];
echo ".$total."
I have a simple calculation using php below, i want to get the sum of total displayed with '+' if the number is positive, eg. '+121', can it be done?
$total = $row["subtotal1"] - $row["subtotal2"];
echo ".$total."
You can echo + sign if your total is greater than 0: echo ($total > 0 ? '+' : '').$total;
$total = 2;
echo ($total > 0 ? '+' : '').$total; // +2
$total = 0;
echo ($total > 0 ? '+' : '').$total; // 0
$total = -1;
echo ($total > 0 ? '+' : '').$total; // -1
You can use a helper function as following:
function getPositiveOrNegative($number){
return ($number >= 0) ? '+' : '';
}
$number = 10;
echo getPositiveOrNegative($number).$number.'<br/>';
$number = -20;
echo getPositiveOrNegative($number).$number.'<br/>';
$number = 0;
echo getPositiveOrNegative($number).$number.'<br/>';
Output:
+10
-20
+0