Skip to content

Commit 5207ec1

Browse files
committed
Add support for float.export option
1 parent 0b79b59 commit 5207ec1

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

src/Encoder/FloatEncoder.php

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class FloatEncoder implements Encoder
1717
private static $defaultOptions = [
1818
'float.integers' => false,
1919
'float.precision' => 17,
20+
'float.export' => false,
2021
];
2122

2223
public function getDefaultOptions()
@@ -53,15 +54,11 @@ private function encodeNumber($float, array $options, callable $encode)
5354
return $this->encodeInteger($float, $encode);
5455
} elseif ($float === 0.0) {
5556
return '0.0';
57+
} elseif ($options['float.export']) {
58+
return var_export($float, true);
5659
}
5760

58-
$precision = $options['float.precision'];
59-
60-
if ($precision === false) {
61-
$precision = ini_get('serialize_precision');
62-
}
63-
64-
return $this->encodeFloat($float, $precision);
61+
return $this->encodeFloat($float, $this->determinePrecision($options));
6562
}
6663

6764
/**
@@ -98,6 +95,22 @@ private function encodeInteger($float, callable $encode)
9895
return number_format($float, 0, '.', '');
9996
}
10097

98+
/**
99+
* Determines the float precision based on the options.
100+
* @param array $options The float encoding options
101+
* @return int The precision used to encode floats
102+
*/
103+
private function determinePrecision($options)
104+
{
105+
$precision = $options['float.precision'];
106+
107+
if ($precision === false) {
108+
$precision = defined('HHVM_VERSION') ? 17 : ini_get('serialize_precision');
109+
}
110+
111+
return max(1, (int) $precision);
112+
}
113+
101114
/**
102115
* Encodes the number using a floating point representation.
103116
* @param float $float The number to encode
@@ -106,7 +119,6 @@ private function encodeInteger($float, callable $encode)
106119
*/
107120
private function encodeFloat($float, $precision)
108121
{
109-
$precision = max(1, (int) $precision);
110122
$log = (int) floor(log(abs($float), 10));
111123

112124
if (abs($float) < self::FLOAT_MAX && $log > -5 && abs($log) < $precision) {

tests/tests/EncodingTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,11 @@ public function testLargeFloatIntegers()
156156
$this->assertEncode('100000000000000000000', 1.0E+20, ['float.integers' => 'all']);
157157
}
158158

159+
public function testFloatExport()
160+
{
161+
$this->assertEncode('1.123', 1.123, ['float.export' => true]);
162+
}
163+
159164
public function testFloatRounding()
160165
{
161166
$encoder = new PHPEncoder(['float.precision' => 14]);

0 commit comments

Comments
 (0)