Skip to content

Commit

Permalink
Fix float export precision
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek authored and sebastianbergmann committed Sep 14, 2022
1 parent 77200c5 commit a9f4590
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
12 changes: 10 additions & 2 deletions src/Exporter.php
Expand Up @@ -209,8 +209,16 @@ protected function recursiveExport(&$value, $indentation, $processed = null)
return 'false';
}

if (\is_float($value) && (float) ((int) $value) === $value) {
return "$value.0";
if (\is_float($value)) {
$precisionBackup = ini_get('precision');
ini_set('precision', '-1');
try {
$valueStr = (string) $value;

return (string) (int) $value === $valueStr ? $valueStr . '.0' : $valueStr;
} finally {
ini_set('precision', $precisionBackup);
}
}

if ($this->isClosedResource($value)) {
Expand Down
21 changes: 15 additions & 6 deletions tests/ExporterTest.php
Expand Up @@ -52,6 +52,13 @@ public function exportProvider()
'export int 1' => [1, '1'],
'export float 1.0' => [1.0, '1.0'],
'export float 1.2' => [1.2, '1.2'],
'export float 1 / 3' => [1 / 3, '0.3333333333333333'],
'export float 1 - 2 / 3' => [1 - 2 / 3, '0.33333333333333337'],
'export float 5.5E+123' => [5.5E+123, '5.5E+123'],
'export float 5.5E-123' => [5.5E-123, '5.5E-123'],
'export float NAN' => [\NAN, 'NAN'],
'export float INF' => [\INF, 'INF'],
'export float -INF' => [-\INF, '-INF'],
'export stream' => [\fopen('php://memory', 'r'), 'resource(%d) of type (stream)'],
'export stream (closed)' => [$resource, 'resource (closed)'],
'export numeric string' => ['1', "'1'"],
Expand Down Expand Up @@ -297,12 +304,14 @@ public function shortenedExportProvider()
];

return [
'shortened export null' => [null, 'null'],
'shortened export boolean true' => [true, 'true'],
'shortened export integer 1' => [1, '1'],
'shortened export float 1.0' => [1.0, '1.0'],
'shortened export float 1.2' => [1.2, '1.2'],
'shortened export numeric string' => ['1', "'1'"],
'shortened export null' => [null, 'null'],
'shortened export boolean true' => [true, 'true'],
'shortened export integer 1' => [1, '1'],
'shortened export float 1.0' => [1.0, '1.0'],
'shortened export float 1.2' => [1.2, '1.2'],
'shortened export float 1 / 3' => [1 / 3, '0.3333333333333333'],
'shortened export float 1 - 2 / 3' => [1 - 2 / 3, '0.33333333333333337'],
'shortened export numeric string' => ['1', "'1'"],
// \n\r and \r is converted to \n
'shortened export multilinestring' => ["this\nis\na\nvery\nvery\nvery\nvery\nvery\nvery\rlong\n\rtext", "'this\\nis\\na\\nvery\\nvery\\nvery...\\rtext'"],
'shortened export empty stdClass' => [new \stdClass, 'stdClass Object ()'],
Expand Down

0 comments on commit a9f4590

Please sign in to comment.