如何回显一个双精度的变量,但只显示小数位数(如果它们是';需要


How do I echo a variable thats a double, but only show the decimal places if they're needed?

我的数据库中有一些双字段,当在php中回显这些字段时,我会在值的末尾得到.00

如何使.00不显示,而是在有值的情况下显示?

您可以使用str_replace从值中删除".00"。

$value = 10.00;
echo str_replace('.00', '', $value); // 10
$value = 10.52;
echo str_replace('.00', '', $value); // 10.52
echo (int)$double;

只需去掉小数点。如果你只想隐藏"零"小数(10.00->10(,但保留非零小数(10.1->10.1(,那么你需要做一些处理:

echo preg_replace('/'.0+$/', '', $double);

它将处理小数点后任意数量的零,但保留非零。

if (fmod($number, 1) == 0)
{
    $number = intval($number);
}
else
{
    $number = round($number, 2);
}

或者只使用round()[@eideone.com]:

var_dump(round($number = 5.00, 2)); // 5
var_dump(round($number = 5.01, 2)); // 5.01

对于任意数量的0 s,位于数字末尾:

$number = rtrim($number,".0");

示例:

Input : 1.00
Result: 1
Input : 1.25
Result: 1.25
Input : 1.40
Result: 1.4
Input : 1.234910120000
Result: 1.23491012
select number,if(number % 1 = 0,cast(number as unsigned),number) 
from table