4

very simple. Consider this code:

var_export (11.2);

this returns with

11.199999999999999

with Php 5.6

wtf?

Walf
  • 8,535
  • 2
  • 44
  • 59
John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 2
    Take a look at https://en.wikipedia.org/wiki/Single-precision_floating-point_format – RiggsFolly Aug 21 '15 at 21:17
  • 2
    Same core question, hardly a dupe imho though. No mention of `var_export` or `serialize_precision` in the linked post. – ficuscr Aug 21 '15 at 21:26
  • 2
    @ficuscr That's hardly relevant. OP is clearly unaware on how floats are represented and printed out. (The "wtf" and silly tags are a dead giveaway). Nothing unique about var_export there. – mario Aug 21 '15 at 21:38
  • 1
    @mario Roger. I'll read up more on the topic. Thanks for responding. Didn't notice the tags till you pointed them out. – ficuscr Aug 23 '15 at 07:26

1 Answers1

4

From the comments on the man page of php.net:

Looks like since version 5.4.22 var_export uses the serialize_precision ini setting, rather than the precision one used for normal output of floating-point numbers. As a consequence since version 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precision value) and not 1.1 as before.

Good to know. I too was not aware of this change.

serialize_precision

Available since PHP 4.3.2. Until PHP 5.3.5, the default value was 100.

So, we can get the behavior we were familiar with using: ini_set('serialize_precision', 100);

Warning

Be very careful when using ini_set(), as this may change behaviour of your code further down the line. A "safe" way would be to use something like this:

$storedValue = ini_get('serialize_precision');
ini_set('serialize_precision', 100);
// Your isolated code goes here e.g var_export($float);
ini_set('serialize_precision', $storedValue);

This ensures that changes further down/deeper in your code is not affected.

Generally, using ini_set() in your code should be considered dangerous, as it can have severe side effects. Refactoring your code to function without the ini_set() is usually a better choice.

Community
  • 1
  • 1
ficuscr
  • 6,975
  • 2
  • 32
  • 52