Skip to content
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

[9.x] Fix decimal cast precision issue #45456

Merged
merged 2 commits into from
Dec 30, 2022

Conversation

timacdonald
Copy link
Member

@timacdonald timacdonald commented Dec 30, 2022

Fixes #45454

Problem

Currently we are handling floats via format_number. Because of number_format, we are losing precision, if the precision is long enough.

Solution

This is a 2 part solution. This PR is part one to address this issue in the least breaking way possible for 9.x and then a follow up PR will fix this using bcmath instead.

To solve this for 9.x we are now manually handling the formatting via the Str helper.

Breaking

number_format rounds numbers when the precision is being reduced. This is no longer the case and I'm not aware of any good way to handle this.

$model = new class extends Model {
    protected $casts = [
        'amount' => 'decimal:1',
    ];
};

$model->amount = '0.99';

// The following test...
// Before ✅
// After ❌

$this->assertSame('1.0', $model->amount);

// The following test...
// Before ❌
// After ✅

$this->assertSame('0.9', $model->amount);

I'm proposing that in 10.x we change this manual string manipulation into a basic bcmath call: #45457

I feel that making bcmath a requirement to use an existing feature could be a breaking change for some applications(?)

@Sjord
Copy link
Contributor

Sjord commented Dec 30, 2022

It looks like this may break on numbers containing exponents, e.g. 0.1e3. Also, should a zero be added if the int part is empty (.1)?

@timacdonald
Copy link
Member Author

Follow up that improves this fix: #45492

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Decimal loses precision because of internal cast to float
3 participants