简体   繁体   中英

PHP minimum precision on a number

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 conversion:

  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM