Skip to content

Commit

Permalink
fix decimal cast precision with bcmath
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald committed Jan 10, 2023
1 parent 0ec041f commit 5bec618
Show file tree
Hide file tree
Showing 3 changed files with 3 additions and 16 deletions.
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@
}
},
"suggest": {
"ext-bcmath": "Required to use the multiple_of validation rule.",
"ext-bcmath": "Required to use the multiple_of validation rule and the Eloquent model decimal attribute cast.",
"ext-ftp": "Required to use the Flysystem FTP driver.",
"ext-gd": "Required to use Illuminate\\Http\\Testing\\FileFactory::image().",
"ext-memcached": "Required to use the memcache cache driver.",
Expand Down
16 changes: 1 addition & 15 deletions src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -1311,21 +1311,7 @@ public function fromFloat($value)
*/
protected function asDecimal($value, $decimals)
{
if (extension_loaded('bcmath')) {
return bcadd($value, 0, $decimals);
}

if (! is_numeric($value)) {
throw new TypeError('$value must be numeric.');
}

if (is_string($value) && Str::contains($value, 'e', true)) {
throw new RuntimeException('The "decimal" model cast is unable to handle string based floats with exponents.');
}

[$int, $fraction] = explode('.', $value) + [1 => ''];

return Str::of($int)->padLeft('1', '0').'.'.Str::of($fraction)->limit($decimals, '')->padRight($decimals, '0');
return bcadd($value, '0', $decimals);
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/Illuminate/Database/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
],
"require": {
"php": "^8.1",
"ext-bcmath": "Required to use the decimal attribute cast.",
"ext-json": "*",
"illuminate/collections": "^10.0",
"illuminate/container": "^10.0",
Expand Down

0 comments on commit 5bec618

Please sign in to comment.