NameUnknown's avatar

Storing float numbers in SQLite

I use SQLite database in my project. I have a table with float columns:

$table->unsignedFloat(column: 'amount', places: 2)->nullable();

My request validation rules are:

'amount' => 'required|numeric',

When I create a model with a float value:

Amount::create([
            'amount' => $request->amount,
]);

values after floating point are lost. Request input 'amount' contains 923442.25, but it is stored as 923442.00

How can I keep the value intact?

0 likes
7 replies
NameUnknown's avatar

@Tray2 Can you provide a code example? Type NUMERIC is automatically assigned to a column during migration, so the column types are correct. But the value is still stored as 923442.00 (with separator and decimals) while the initial value is 923442.25

Tray2's avatar
Tray2
Best Answer
Level 74

@NameUnknown There seems to be a bit of a debate how to store it in SQLIte. I suggest multiply with 100 and then divide with 100 before displaying

1 like
NameUnknown's avatar

@Tray2 So there is no universal approach, then? Is it feasible to store floats as strings and just to convert them when reading?

Tray2's avatar

@NameUnknown Yeah, but floats aren't the best thing to use, they are not exact, they can differ a bit.

1 like
amariano1989's avatar

@NameUnknown use ROUND () function. I'm new to SQL and SQLite; currently studying the syntax. Example: SELECT (ROUND(59)/ROUND(1000))*100 as 'Result'; will give you 5.9

Please or to participate in this conversation.