Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kennybjr87's avatar

Decimals being turned into a string

I've spent a good amount of time trying to figure out why my decimals are being turned into a string I've used casting on my model. I've done some searching but however, I'm not finding a working answer. Some suggested casting to a float but isn't a float bad practice for dealing with actual prices? I should mention I'm using Laravel 5.8 and MariaDB

  $table->decimal('total', 6, 2);
0 likes
7 replies
bobbybouwmann's avatar

A decimal field in the database is basically a float, so a float should be good here!

If you want to store money in the database it's better to use plain integers. So for example if you have price of 5.67 you insert 567 in the database. From there you can convert it back to 5.67 if you wish ;)

staudenmeir's avatar

Using strings and the BCMath library is the only precise way to handle decimal values in PHP (besides using integers).

@bobbybouwmann Decimal and float are not "basically the same", they are very different. You should never store precise data like amounts of money as a float. Rounding errors will mess up your calculations.

1 like
kennybjr87's avatar

@JLRDW - All I'm doing is just pulling right from the DB?

{
"id": 2,
"invoice_id": 19,
"item_number": "96252635",
"description": "Ut voluptate veniam non deserunt aut.",
"unit_cost": "3.00", //string
"quantity": 0,
"price": "3.00", //string
"created_at": "2019-03-09 15:36:48",
"updated_at": "2019-03-09 15:36:48"
},
jlrdw's avatar

MySql knows what to do with the data when you post for example.

As an example say you have a form And Post to a controller method, strings are posted.

Just make sure in MySQL you have that field defined as decimal.

PHP has a lot of loose casting whereas if you were working with c# do you would have to properly cast everything.

Take note that date and time stamps are quoted also but when inserted into the database MySQL will take care of you.

Please or to participate in this conversation.