0

I have an issue with php 5.6 rounding to two decimals. If you test the following it will export $y exactly as 19.620000000000001

I know there are solutions to display it using number_format, but how do I make it to be exactly 19.62?

Thanks.

$x = 19.620000000000001;
$y = round($x, 2);
var_export($y);

Later Edit. I need it for exact math operations, not display.

Alexandru R
  • 8,560
  • 16
  • 64
  • 98
  • reference https://stackoverflow.com/questions/588004/is-floating-point-math-broken – DarkBee Jan 04 '18 at 08:53
  • You need to do some reading up on floating-point numbers. One of the things that you need to learn first and foremost is there is no such thing as exact in floating point. – GordonM Jan 11 '18 at 09:40

3 Answers3

3

Try using echo to display your output. It will give you your desired output

Miggy
  • 816
  • 7
  • 16
2

It's because you're using var_export

Try using echo or var_dump()

$x = 19.620000000000001;
$y = round($x, 2);
echo $y;
MrPerry95
  • 29
  • 1
  • 1
  • 8
0

If you do number_format:

$y = number_format($x, 2);

The $y will have 2 decimals but it will also be a string. Not sure if it's satisfactory.

Mat
  • 2,378
  • 3
  • 26
  • 35
  • @AlexandruRada you didn't say you need it for math operations. You said "to display it", but yeah, you probably can't casue it's a string, as I mentioned. – Mat Jan 09 '18 at 14:49