2

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.

Aleksandr Popov
  • 500
  • 5
  • 20

1 Answers1

4

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.

Alex Harris
  • 6,172
  • 2
  • 32
  • 57
  • Thank you! Looks like I could not find right keywords to find that but anyway I will double check. – Aleksandr Popov Jun 01 '18 at 05:17
  • What I did is I have added following method in my Model: `public function getPreviousValueAttribute($value) { ini_set('precision', 17); return $value; }` . That will definitely bring correct value in output. Ofcourse I will put that in configuration in future. @alex-harris thanks for pointing me to solution! – Aleksandr Popov Jun 01 '18 at 06:20
  • More general solution would be to put that into `constructor` like this: `public function __construct() { ini_set('precision', 17); parent::__construct(); }`. – Aleksandr Popov Jun 01 '18 at 06:54