PHP 实数小数点后一位,整数无数字

PHP one digit after decimal point for real numbers and no digits for integer values

将数字转换为的最佳解决方案是什么:

  1. 小数点后一位如果是实数
  2. 没有数字,如果数字是整数则没有小数点

示例:

if ($num == 8.2) //display 8.2
if ($num == 8.0) //display 8

注意:我不会使用 8.22 或 8.02 这样的数字。我会有这种类型的数字:

1, 1.2, 1.4 ... 2.6, 2.8, 3 ....9.8, 10

if (abs($num - (int)$num) < 0.001)
  echo (int)$num;
else
  echo number_format($num, 1);

使用 floor 和一些算术和 number_format

$num = 8.0;

//8.0 - 8 = 0
//8.2 - 8 = .2
if($num - floor($num)>0) {
    // Leaves 1 decimal
    echo number_format($num,1);
    // or if rounding
    //echo round($num, 1);
} else {
    // Leaves 0 decimal
    echo number_format($num,0);
    // or if rounding
    //echo round($num, 0);
}

如果您确定所有号码都将采用该格式,您应该可以只使用 round。 (通常,round 不能 很好地格式化,但在这种情况下它应该可以完成工作。)

foreach ([8, 8.2, 1, 1.2, 1.4, 2.6, 2.8, 3, 9.8, 10] as $number) {
    echo round($number, 1) . PHP_EOL;
}

有些人可能有其他假设,但 echo round(8.0, 1); 显示 8,而不是 8.0