I was asked to add a column containg the bonuses of salary of employees, examples of this values were give such as: 1099.99 or 2.00. Task also asked me to add appropriate data type but I was confused which one to use.
I tried using both double and float and couldn’t differenciate between the results. So, help me choose appropriate datatype.
2
Answers
Regarding to the official documentation, we have the next diferences:
You can ask about differences between floating and fixed datatypes, but this is not so easy to describe, try to read the same official documentation, or this article, for example.
Computer scientist Brian Kernighan wrote:
FLOAT
andDOUBLE
are both IEEE 754 format values. They store a wide range of floating-point value, including very small or very large values, but they have the disadvantage that they have rounding errors.For examples and details on that, read:
FLOAT
stores 32 bits andDOUBLE
stores 64 bits. This just means you can store more significant digits with aDOUBLE
, but it still has the same rounding behavior.These data types are good for scientific measurements like temperature, where the difference between 39 degrees and 38.999999997 degrees won’t make a significant difference, especially if you’re only doing things like averages or standard deviations.
Because of the rounding behavior,
FLOAT
andDOUBLE
should never be used to store values of currency.For currency values (e.g. the salaries you need to store), use
DECIMAL
.DECIMAL
andNUMERIC
are exact scaled numerics. You define a column with a specific number of digits, and a specific number of digits to the right of the decimal point. There are no rounding problems; values you store come right back out exactly as you stored them. You can search the data for specific values.DECIMAL
andNUMERIC
are synonyms. There’s no difference. In fact, if you useNUMERIC
as the type, MySQL silently replaces it withDECIMAL
.You may also like to read the chapter "Rounding Errors" in my book, SQL Antipatterns, Volume 1: Avoiding the Pitfalls of Database Programming.