Search code examples
phpprintfnumber-formatting

Unexpected result for number_format and sprintf when trying to display number with two decimals


I have a calculation that returns this double: 6.4971508379888. If I cast it to a float and echo it, it's the same number. I want to display (not round) the number with only two decimals, so I tried:

number_format((float)$number, 2, '.', '')

and

sprintf('%0.2f', (float)$number)

but in both cases I see 6.50 instead of 6.49. Why is this happening?


Solution

  • PHP automatically round the value based on given precision

    If you want your expected results then follow the following code.

    $precision = 2;
    $number = floor($number * pow(10,$precision))/pow(10,$precision);
    echo number_format((float)$number, $precision, '.', '');