Skip to content

[Form] Fix precision loss when rounding large integers in NumberToLocalizedStringTransformer #60975

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 6.4
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,10 @@ protected function castParsedValue(int|float $value): int|float
*/
private function round(int|float $number): int|float
{
if (\is_int($number)) {
return $number;
}

if (null !== $this->scale && null !== $this->roundingMode) {
// shift number to maintain the correct scale during rounding
$roundingCoef = 10 ** $this->scale;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -726,4 +726,33 @@ public static function eNotationProvider(): array
[1232.0, '1.232e3'],
];
}

public function testReverseTransformDoesNotCauseIntegerPrecisionLoss()
{
$transformer = new NumberToLocalizedStringTransformer();

// Test a large integer that causes actual precision loss when cast to float
$largeInt = \PHP_INT_MAX - 1; // This value loses precision when cast to float
$result = $transformer->reverseTransform((string) $largeInt);

$this->assertSame($largeInt, $result);
$this->assertIsInt($result);
}

public function testRoundMethodKeepsIntegersAsIntegers()
{
$transformer = new NumberToLocalizedStringTransformer(2); // scale=2 triggers rounding

// Use reflection to test the private round() method directly
$reflection = new \ReflectionClass($transformer);
$roundMethod = $reflection->getMethod('round');
$roundMethod->setAccessible(true);

$int = \PHP_INT_MAX - 1;
$result = $roundMethod->invoke($transformer, $int);

// With the fix, integers should stay as integers, not be converted to floats
$this->assertSame($int, $result);
$this->assertIsInt($result);
}
}
Loading