mysqldatabasecurrencysqldatatypes

What's difference between float, double and decimal in sql?


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.


Solution

  • "No difference"? That was lucky.

    Use DECIMAL(m,n) for money. For many currencies, DECIMAL(m,2), where m is big enough so that you won't overflow even when the CEO gets a big raise. DECIMALoccupies _approximately_ m/2 bytes. 1 billion dollars or Euros needs(11,2)` and takes 5 bytes.

    FLOAT and DOUBLE are for measurements. FLOAT occupies 4 bytes and has about 7 significant digits -- plenty for temperature, speed, height, etc. DOUBLE` (8 bytes) gives you about 16 significant digits; it may be needed from some very precise scientific research.

    Latitude and Longitude -- FLOAT is precise though to distinguish two vehicles on the road, but not to distinguish two people embracing. See also https://mysql.rjweb.org/doc.php/latlng#representation_choices

    For various reasons (many not listed here), none of the representations can be trusted to round "correctly" according to banking rules when multiplying or dividing. Addition of dollars and cents will be exact with DECIMAl.