Skip to content

Commit 90892f9

Browse files
Correct implementation of float casting comparison (#33322)
1 parent 30441e8 commit 90892f9

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,6 +1178,8 @@ public function originalIsEquivalent($key, $current)
11781178
} elseif ($this->hasCast($key, ['object', 'collection'])) {
11791179
return $this->castAttribute($key, $current) ==
11801180
$this->castAttribute($key, $original);
1181+
} elseif ($this->hasCast($key, ['real', 'float', 'double'])) {
1182+
return abs($this->castAttribute($key, $current) - $this->castAttribute($key, $original)) < PHP_FLOAT_EPSILON * 4;
11811183
} elseif ($this->hasCast($key)) {
11821184
return $this->castAttribute($key, $current) ===
11831185
$this->castAttribute($key, $original);

tests/Database/DatabaseEloquentModelTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,19 @@ public function testCleanAttributes()
148148
$this->assertFalse($model->isClean(['foo', 'bar']));
149149
}
150150

151+
public function testCleanWhenFloatUpdateAttribute()
152+
{
153+
// test is equivalent
154+
$model = new EloquentModelStub(['castedFloat' => 8 - 6.4]);
155+
$model->syncOriginal();
156+
$this->assertTrue($model->originalIsEquivalent('castedFloat', 1.6));
157+
158+
// test is not equivalent
159+
$model = new EloquentModelStub(['castedFloat' => 5.6]);
160+
$model->syncOriginal();
161+
$this->assertFalse($model->originalIsEquivalent('castedFloat', 5.5));
162+
}
163+
151164
public function testCalculatedAttributes()
152165
{
153166
$model = new EloquentModelStub;
@@ -1992,6 +2005,7 @@ class EloquentModelStub extends Model
19922005
protected $table = 'stub';
19932006
protected $guarded = [];
19942007
protected $morph_to_stub_type = EloquentModelSaveStub::class;
2008+
protected $casts = ['castedFloat' => 'float'];
19952009

19962010
public function getListItemsAttribute($value)
19972011
{

0 commit comments

Comments
 (0)