From e53806e99c847174a99f167febc2eb6995d68c69 Mon Sep 17 00:00:00 2001 From: Nicolas Grekas Date: Fri, 9 Oct 2026 17:38:55 +0200 Subject: [PATCH] Fix compiled float literals depending on the serialize_precision ini setting --- CHANGELOG | 1 + src/Compiler.php | 7 +++++++ tests/CompilerTest.php | 13 +++++++++++++ 3 files changed, 21 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 9ba632217..e4ca7f044 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ # 3.31.0 (2026-XX-XX) + * Fix compiled float literals depending on the `serialize_precision` ini setting * Fix the `loop` variable being undefined when used in the sequence of a nested `for` tag * Reject a deprecated `Template` instance created by another environment in `Environment::resolveTemplate()` * Fix a compilation error inside an `autoescape` tag leaking its escaping strategy into the next compiled template diff --git a/src/Compiler.php b/src/Compiler.php index 976030f79..b3f23d09f 100644 --- a/src/Compiler.php +++ b/src/Compiler.php @@ -166,8 +166,15 @@ class Compiler setlocale(\LC_NUMERIC, 'C'); } + // var_export() follows serialize_precision, -1 gives the shortest representation that reads back as the same float + $precision = \is_float($value) ? ini_set('serialize_precision', '-1') : false; + $this->raw(var_export($value, true)); + if (false !== $precision) { + ini_set('serialize_precision', $precision); + } + if (false !== $locale) { setlocale(\LC_NUMERIC, $locale); } diff --git a/tests/CompilerTest.php b/tests/CompilerTest.php index d3d192552..869f78019 100644 --- a/tests/CompilerTest.php +++ b/tests/CompilerTest.php @@ -64,4 +64,17 @@ class CompilerTest extends TestCase setlocale(\LC_NUMERIC, $locale); } + + public function testReprFloatDoesNotDependOnSerializePrecision(): void + { + $compiler = new Compiler(new Environment(new ArrayLoader())); + $precision = ini_set('serialize_precision', '17'); + + try { + $this->assertSame('0.1', $compiler->repr(0.1)->getSource()); + $this->assertSame('17', \ini_get('serialize_precision')); + } finally { + ini_set('serialize_precision', $precision); + } + } }