Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 406
Mike Valstar Avatar asked Aug 31 '10 16:08

Mike Valstar


Video Answer


2 Answers

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
like image 57
matja Avatar answered Sep 24 '22 07:09

matja


$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

like image 31
Kusanagi2k Avatar answered Sep 24 '22 07:09

Kusanagi2k