我有一个来自数据库的数字列表,范围从0.001到10,我需要以最小精度显示2位小数但没有最大精度。
示例数字和预期转换:
任何想法?
答案 0 :(得分:7)
function min_precision($x, $p)
{
$e = pow(10,$p);
return floor($x*$e)==$x*$e?sprintf("%.${p}f",$x):$x;
}
foreach (Array(1,0.1,0.01,0.001,1.234,0.035,25.5) as $x)
{
echo $x . " -> " . min_precision($x,2) . "\n";
}
输出:
1 -> 1.00
0.1 -> 0.10
0.01 -> 0.01
0.001 -> 0.001
1.234 -> 1.234
0.035 -> 0.035
25.5 -> 25.50
答案 1 :(得分:3)
$number = split('.', $dbNumber);
if(strlen($number[1]) < 2)
$resultNumber = number_format($dbNumber,2);
else
$resultNumber = $dbNumber;
其中$ dbNumber是来自数据库的数字
答案 2 :(得分:0)
number_format(25.5, 2)