views:

39

answers:

3

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?

A: 

number_format(25.5, 2)

http://us.php.net/number_format

efritz
Yes but number_format(0.1234, 2) will result in 0.12
Mike Valstar
-1: didn't read question
Hammerite
no maximum precision... too little too late!
efritz
+3  A: 
$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

Kusanagi2k
+1  A: 
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
matja