Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store a field PRICE as an int or as a float int the database?

Tags:

database

mysql

In a previous project, I noticed that the price field was being stored as an int, rather than as a float. This is done by multiplying the actual value by 100, the reason being was to avoid running into floating point problems.

Is this a good practice that I should follow or is it unnecessary and only makes the data less transparent?

like image 281
Mark Basmayor Avatar asked Jan 29 '10 10:01

Mark Basmayor


People also ask

What data type should I use for price in SQL?

The best type for price column should be DECIMAL. The type DECIMAL stores the value precisely. For Example - DECIMAL(10,2) can be used to store price value. It means the total digit will be 10 and two digits will be after decimal point.

Which data type is best for currency amounts?

BigDecimal for the Rescue That's the reason we should always prefer BigDecimal or BigInteger for financial calculations. Primitive type — int and long are also useful for monetary calculations if decimal precision is not required.

Is price an int or string?

Prices should be stored as DECIMAL or INT, because they have a fixed number of decimal points.

Can I store float in int or not?

So you cannot store a float value in an int object through simple assignment. You can store the bit pattern for a floating-point value in an int object if the int is at least as wide as the float , either by using memcpy or some kind of casting gymnastics (as other answers have shown).


2 Answers

Interesting question.

I wouldn't actually choose float in the mysql environment. Too many problems in the past with precision with that datatype.

To me, the choice would be between int and decimal(18,4).

I've seen real world examples integers used to represent floating point values. The internals of JD Edwards datatables all do this. Quantities are typically divided by 10000. While I'm sure it's faster and smaller in-table, it just means that we're always having to CAST the ints to a decimal value if we want to do anything with them, especially division.

From a programming perspective, I'd always prefer to work with decimal for price ( or money in RDBMSs that support it ).

like image 171
Paul Alan Taylor Avatar answered Oct 12 '22 14:10

Paul Alan Taylor


Floating point errors could cause you problems if you are multiplying large numbers. In general, financial calculations should never be done with floating point numbers where possible.

like image 23
cjk Avatar answered Oct 12 '22 15:10

cjk