1

Strange error that I can't seem to find the cause of: my decimal numbers are being automatically rounded when saved to database - only when I use PHP 7.3. The problem doesn't occur when using PHP 7.1 (I'm switching between the 2 versions using whm's multi php manager)

10.1.39-MariaDB Laravel 5.5, using eloquent, tested by doing:

$model->num=1.23;
$model->save();

Works fine when using php 7.1, the value 1.23 I saved correctly to the database, however when using php 7.3 the value is rounded down to 1.00.

I can see that the actual SQL sent by laravel's query builder is correct in both cases: UPDATE x SET num=1.23 WHERE id=x so somewhere inbetween the query builder and actual execution the value is being rounded.

I also wrote a pure php test without using Laravel using mysqli_query("UPDATE ...") and this works correctly in both php versions, so I'm thinking that the problem must be in some Laravel database package incompatibility perhaps.

Don't really know where to go from here - any advise anyone?

Thanks in advance.

UPDATE

On php 7.3 I get the value saved to db correctly if I cast to string first:

$model->num= (string)1.23;
$model->save();

I don't really want to do this though as there will be many places I'd have to do this... still investigating the cause

5
  • are you using the same database every time, and what is the data type on the column? Commented Nov 25, 2019 at 3:38
  • Yes - same database every time and column is double(10,2) Commented Nov 25, 2019 at 3:42
  • Just to confirm if it is the data type that's causing the error, is it possible to change column to a decimal and check? Commented Nov 25, 2019 at 3:46
  • done - changed column type to decimal - no change, still error. tried changing column type to string also - no change Commented Nov 25, 2019 at 3:49
  • I see. I thought maybe there was a very slight chance that double was causing it because double is known to cause rounding errors. I'll try and see if I can reproduce this. Commented Nov 25, 2019 at 3:55

1 Answer 1

1

Use number_format($value, 2) It will be definitely works.

Detail format is: number_format($value, 2, '.', '');

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

1 Comment

yes, but that's effectively the same as casting to string.

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.