【问题标题】:php display positive number with '+' sign [closed]php用'+'号显示正数[关闭]
【发布时间】:2020-07-12 11:55:26
【问题描述】:

我在下面使用 php 进行了一个简单的计算,如果数字是正数,我想得到用“+”显示的总和,例如。 '+121',可以吗?

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

echo ".$total."

【问题讨论】:

标签: php


【解决方案1】:

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

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 2012-06-04
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 2013-03-22
      • 2013-03-02
      • 1970-01-01
      相关资源
      最近更新 更多