Aleksandr Popov
Aleksandr Popov

Reputation: 520

Laravel Eloquent double value stored in database returned rounded

I have following value stored in MySQL database 23456789123,45678 and when I'm getting this value using magic variable I'm getting 23456789123,457 as a value.

I have tried $cast variable in Model:

protected $casts = [
  'previous_value' => 'double(16,5)',
]

but that did not helped. Much appreciate on any help in this regards.

Upvotes: 2

Views: 2984

Answers (1)

Alex Harris
Alex Harris

Reputation: 6392

The problem is not with Laravel, it is actually PHP that is rounding this. In the PHP documentation you can see that the default precision is 14, which you are currently exceeding.

Name      |   Default |   Changeable   |
precision |   "14"    |   PHP_INI_ALL  |

The number of significant digits displayed in floating point numbers. -1 means that an enhanced algorithm for rounding such numbers will be used.

Try the following and see if it resolves the issue:

ini_set('precision', 17);
ExampleModel::find($id)->previous_value;

You can see someone else has answered a similar question here.

Upvotes: 4

Related Questions