开发者

PHP minimum precision on a number

开发者 https://www.devze.com 2023-01-14 13:07 出处:网络
I have a list of numbers coming from a database that range from0.001 to 10 and I need to display them with a minimum precision of 2 decimal places but no maximum precision.

I have a list of numbers coming from a database that range from 0.001 to 10 and I need to display them with a minimum precision of 2 decimal places but no maximum precision.

Example numbers and expected conve开发者_运维问答rsion:

  • 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

Any Ideas?


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";
}

output:

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


$number = split('.', $dbNumber);
if(strlen($number[1]) < 2)
     $resultNumber = number_format($dbNumber,2);
else
     $resultNumber = $dbNumber;

where $dbNumber is the number coming from the datababase


number_format(25.5, 2)

http://us.php.net/number_format

0

精彩评论

暂无评论...
验证码 换一张
取 消