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.

2
  • How your db structure? Commented May 31, 2018 at 15:18
  • it is sotred as double(16,5) ie: $table->double('previous_value', 16, 5)->nullable(); Commented May 31, 2018 at 15:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! Looks like I could not find right keywords to find that but anyway I will double check.
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!
More general solution would be to put that into constructor like this: public function __construct() { ini_set('precision', 17); parent::__construct(); }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.