Skip to content

Commit

Permalink
FIX Improve rounding logic for storing of long decimal numbers (#10593)
Browse files Browse the repository at this point in the history
Co-authored-by: Michal Kleiner <michal.kleiner@cub3.com>
  • Loading branch information
michalkleiner and Michal Kleiner committed Nov 29, 2022
1 parent f57a77d commit b107622
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/ORM/FieldType/DBDecimal.php
Expand Up @@ -126,7 +126,7 @@ public function prepValueForDB($value)
return 0;
}

if (ctype_digit((string) $value)) {
if (abs((float) $value - (int) $value) < PHP_FLOAT_EPSILON) {
return (int)$value;
}

Expand Down
29 changes: 29 additions & 0 deletions tests/php/ORM/DecimalTest.php
Expand Up @@ -61,6 +61,35 @@ public function testSpecifiedDefaultValueInDefaultsArray()
);
}

public function testLongValueStoredCorrectly()
{
$this->assertEquals(
$this->testDataObject->MyDecimal5,
1.0,
'Long default long decimal value is rounded correctly'
);

$this->assertEqualsWithDelta(
$this->testDataObject->MyDecimal5,
0.99999999999999999999,
PHP_FLOAT_EPSILON,
'Long default long decimal value is correct within float epsilon'
);

$this->assertEquals(
$this->testDataObject->MyDecimal6,
8.0,
'Long decimal value with a default value is rounded correctly'
);

$this->assertEqualsWithDelta(
$this->testDataObject->MyDecimal6,
7.99999999999999999999,
PHP_FLOAT_EPSILON,
'Long decimal value is within epsilon if longer than allowed number of float digits'
);
}

public function testScaffoldFormField()
{
/** @var DBDecimal $decimal */
Expand Down
7 changes: 5 additions & 2 deletions tests/php/ORM/DecimalTest/TestObject.php
Expand Up @@ -14,10 +14,13 @@ class TestObject extends DataObject implements TestOnly
'MyDecimal1' => 'Decimal',
'MyDecimal2' => 'Decimal(5,3,2.5)',
'MyDecimal3' => 'Decimal(4,2,"Invalid default value")',
'MyDecimal4' => 'Decimal'
'MyDecimal4' => 'Decimal',
'MyDecimal5' => 'Decimal(20,18,0.99999999999999999999)',
'MyDecimal6' => 'Decimal',
];

private static $defaults = [
'MyDecimal4' => 4
'MyDecimal4' => 4,
'MyDecimal6' => 7.99999999999999999999,
];
}

0 comments on commit b107622

Please sign in to comment.