Question

I have a DOUBLE data type column in my MySQL table and I have a value of:

14.5299

But PHP number_format rounds that value to:

14.5300 

And if I just echo 14.5299, it outputs:

14.53

How can I output 14.5299 without hardcoding anything in my HTML markup?

Was it helpful?

Solution

Use sprintf()

echo sprintf("%2.4f", 14.5399);

Documentation: http://us2.php.net/sprintf

OTHER TIPS

This worked for me:

<?php
$double = 14.5299;
echo number_format(floor($double*100)/100, 2);
?>

Result is: 14.52

$double = 14.5299;
var_dump( number_format($double, 4, '.', ',') );

... prints:

string(7) "14.5299"

... as expected.

My educated guess is that your number has actually more 9's:

$double = 14.52999;

... in this case, 14.5300 is the correct way to round.

The next function should works:

function fixedNumberFormat($float, $decimals, $withFormat = true) {
   $decPoint = ($withFormat) ? "," : null;
   $thousandsSep = ($withFormat) ? "," : null;
   return substr(number_format($float, $decimals + 1), 0, -1);
}

fixedNumberFormat(14.5299, 4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top