-2

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."
Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
robin
  • 171
  • 1
  • 6
  • 23
  • 1
    Does this answer your question? [How to prefix a positive number with plus sign in PHP](https://stackoverflow.com/questions/2682397/how-to-prefix-a-positive-number-with-plus-sign-in-php) – Spatz Jul 13 '20 at 05:53

2 Answers2

2

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
blahy
  • 1,294
  • 1
  • 8
  • 9
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