2

The Symfony\Component\HttpFoundation\JsonResponse seems to have an odd reaction.

I retrieve a Doctrine "decimal" parameter from my object list and I try to send an array of them with a JsonResponse. But the decimal value is not the one I expected, the "precision" is really odd, and I'm unable to round it :

My Entity :

...

/**
 * @var float Local average Grade
 * @ORM\Column(type="decimal", nullable=true, precision=4, scale=2)
 */
private $grade;

...

For this example, I will use only a single result of my data. When I read it from the database, I can read, as expected : 8.30

Here are the tests I've made :

var_dump(gettype($local->getGrade()));
var_dump($local->getGrade());
var_dump((float) $local->getGrade());
var_dump(round($local->getGrade(), 2));


return new JsonResponse([
    'grade' => $local->getGrade(),
    'roundedGrade' => round($local->getGrade(), 2)
]);

And here is the result :

string(6) "string"
string(4) "8.10"
float(8.1)
float(8.1) 

{
    "grade":8.0999999999999996447286321199499070644378662109375,
    "roundedGrade":8.0999999999999996447286321199499070644378662109375
}

It doesn't make sense to me. Does anyone have any idea of what is happening here ?

Thank you.

Jason Roman
  • 8,146
  • 10
  • 35
  • 40
Thibault Henry
  • 816
  • 6
  • 16
  • 1
    https://www.leaseweb.com/labs/2013/06/the-php-floating-point-precision-is-wrong-by-default/ – Doug Jul 06 '17 at 20:06
  • This might also interest you, since you stumbled upon the good old "float problem in programming": https://stackoverflow.com/questions/1642614/how-to-ceil-floor-and-round-bcmath-numbers (and you'll want to utilize the bcmath package because, well, we all love our decimal numbers to read what we expect them to read ^^ ) – Tom De Roo Jul 06 '17 at 21:03

1 Answers1

1

Try this:

echo number_format((float)$local->getGrade(), 2, '.', ''); //8.10
Imanali Mamadiev
  • 2,604
  • 2
  • 15
  • 23
  • That return a string a not a float, but I can work with it. Thank you. (Even if I don't understand what happen different here) – Thibault Henry Jul 06 '17 at 20:25