提问者:小点点

php显示带“+”符号的正数


我有一个简单的计算使用php下面,我想得到的总和显示与'+'如果数字是正的,例如。 '+121',能做到吗?

$total = $row["subtotal1"] - $row["subtotal2"];

echo ".$total."

共2个答案

匿名用户

您可以按以下方式使用帮助器函数:

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/>';

输出:
+10
-20
+0

匿名用户

如果总数大于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