MySQL FLOAT Type: Precision Pitfalls and Best Practices

目次

1. Introduction

Choosing Numeric Types in Databases Is Surprisingly Important

MySQL is an open-source database management system widely used around the world. It is utilized as the backend for web applications and as the foundation for CMS platforms like WordPress, making it an indispensable tool for developers.

Among these considerations, deciding “which type to use for storing numeric data” is a very important decision that directly impacts performance and precision. In addition to integer types (INT, BIGINT, etc.), for handling decimals, options include floating-point types (FLOAT and DOUBLE) and fixed-point types (DECIMAL).

In this article, we will focus particularly on the “FLOAT type” and provide a detailed explanation.

What Is MySQL’s FLOAT Type?

Many of you who arrived here by searching for “mysql float” are probably wondering things like:

  • What kind of type is the FLOAT type?
  • What are the differences between the FLOAT type, DOUBLE type, and DECIMAL type?
  • Are there precision issues?
  • Is it okay to use it for data like amounts, weights, or ratios?

To answer these questions, this article will cover the basics of the FLOAT type, advanced applications, precautions, comparisons with other types, and practical advice in detail.

Knowledge to Avoid Troubles in Practice

If you use the FLOAT type without understanding its properties, it can lead to unexpected data inconsistencies or calculation errors. On the other hand, if you correctly understand its characteristics, it can be very effective as a means to efficiently process data in MySQL.

This article is written with the goal that by the time you finish reading it, you who are searching for the keyword “mysql float” will have acquired the ability to use the FLOAT type appropriately. Please read to the end.

2. What is the FLOAT Type?

Basics of the FLOAT Type in MySQL

In MySQL, the FLOAT type is a data type for storing floating-point numbers. This is used in situations where handling numbers with decimals is required, and it provides approximate numerical representations.

As the name floating-point suggests, the decimal point position of the number is not fixed, and its feature is that it can flexibly represent from large numbers to very small numbers. It is an effective type in cases such as scientific calculations or sensor values where some error is tolerable.

CREATE TABLE sample (
  value FLOAT
);

If defined as above, it becomes possible to store floating-point numbers in that column.

Size and Precision of the FLOAT Type

The FLOAT type is a single precision floating-point type. Approximately 7 digits of significant figures are guaranteed, and digits beyond that may be rounded internally.

This specification is based on the IEEE 754 standard, and while it is not suitable for precise calculations of amounts or statistical values, it is valuable for uses processing large amounts of data quickly and with low memory usage.

Syntax and Usage of the FLOAT Type

In MySQL, it can be defined in the form FLOAT(M,D). At this time, M and D have the following meanings:

  • M: Total number of digits (integer part + decimal part)
  • D: Number of decimal places

For example, it can be defined as follows:

CREATE TABLE prices (
  price FLOAT(7,4)
);

In this case, the price column can store up to 7 digits of numbers, of which 4 digits are allocated after the decimal point. Thus, the effective range is -99999.99 to 99999.99.Note:Even if you specify FLOAT(M,D), since floating-point operations are performed internally, strict guarantee of the number of digits is not always provided, so please be careful. It is good to think of it as a rough guide for the number of display digits after the decimal point.

3. Precision and Range of the FLOAT Type

Relationship Between Significant Digits and Errors

MySQL’sFLOAT type is implemented as a single-precision floating-point number based on IEEE 754. This means that approximately 7 significant digits are guaranteed. In other words, values exceeding 7 digits may be rounded.

For example, when storing a value like the following:

INSERT INTO sample (value) VALUES (1234567.89);

This value may seem fine at first glance, but due to the precision limitations of the FLOAT type, it may become a slightly different value after storage. This is called a rounding error and is a characteristic specific to floating-point types.

Actual Example: Occurrence of Errors

Let’s consider a comparison like the following.

SELECT value = 0.1 FROM sample WHERE id = 1;

Even if 0.1 is INSERTed into the value column, this comparison may not return TRUE. This is because the value 0.1 cannot be exactly represented in binary on a computer, resulting in a slight discrepancy the moment it is stored in the FLOAT type.

If such errors accumulate, they can affect aggregation results or conditional branching.

Representable Numeric Range of the FLOAT Type

The numeric range of the FLOAT type is very wide. According to the official MySQL documentation, it covers a range of approximately ±1.17549 × 10^(-38) to ±3.40282 × 10^(38).

This provides a sufficient range for typical web applications or recording sensor values, but caution is needed for financial applications that require precision.

Focus More on “Precision” Than on Range

When using the FLOAT type, the most important thing to note is not the breadth of the numeric range, but the limitations of precision. Issues arising from the inability to match values exactly are more serious in practice than the ability to handle large or small values.

Therefore, rather than selecting the FLOAT type based solely on the magnitude of the values, you should base the decision on “how much error is acceptable for that value”.

4. FLOAT Type Syntax and Usage

Basic Definition Method

In MySQL, the most basic way to define a FLOAT type column is as follows.

CREATE TABLE products (
  weight FLOAT
);

In this example, you can store floating-point numbers in the weight column. If you don’t need to specify the precision or number of digits, this is sufficient.

Meaning and Usage of FLOAT(M,D)

If a more detailed definition is needed, use the FLOAT(M,D) format.

  • M is the total number of digits (integer part + decimal part)
  • D is the number of digits in the decimal part

For example, you can define it as follows:

CREATE TABLE prices (
  price FLOAT(7,4)
);

In this case, the price column can store up to 7 digits, with 4 of them allocated after the decimal point. Thus, the valid range is -99999.99 to 99999.99.Note:Even if you specify FLOAT(M,D), since floating-point operations are performed internally, strict guarantee of the number of digits is not always provided. It’s best to think of it as a guideline for the number of decimal places displayed.

Specifying UNSIGNED (Unsigned)

You can attach the UNSIGNED modifier to the FLOAT type. This excludes negative values and allows storage of only non-negative numbers (0 and above).

CREATE TABLE ratings (
  score FLOAT UNSIGNED
);

This way, negative numbers cannot be stored in the score column, which helps maintain data integrity.

Using ZEROFILL (Zero Padding)

Specifying ZEROFILL will pad with zeros when the number of digits is insufficient in the display of the number. It is premised on using it in combination with M (number of digits).

CREATE TABLE inventory (
  amount FLOAT(5,2) ZEROFILL
);

With the above setting, storing 3.5 will display it as 003.50. However, this only changes the display appearance; the actual value does not change.

Example of INSERT and SELECT for FLOAT Type Values

INSERT INTO products (weight) VALUES (12.345);

SELECT weight FROM products;

Values stored this way will be displayed as is during SELECT. However, as mentioned earlier, keep in mind that there may be slight discrepancies in the display.

5. Advantages and Disadvantages of the FLOAT Type

Advantages of the FLOAT Type

Using the FLOAT type in MySQL has several practical advantages.

1. High Storage Efficiency

The FLOAT type is stored in 4 bytes, so in databases that need to store a large number of decimals, it can save storage space. For example, it is effective in scenarios handling large volumes of high-frequency data such as sensor data or statistical records.

2. Fast Processing Speed

Floating-point operations are optimized at the hardware level on many CPUs, making the calculation speed very fast. This is a significant advantage for real-time systems or analytical processing where processing performance is important.

3. Can Represent Very Large or Very Small Values

Since the FLOAT type has an exponent part, it can represent a very wide range of numerical values. It can handle up to approximately ±10^38, so it can accommodate astronomical values or extremely small values.

Disadvantages of the FLOAT Type

On the other hand, the FLOAT type also has non-negligible drawbacks. Especially in applications where precision is required, careful judgment is necessary.

1. Precision May Be Inaccurate

The FLOAT type is stored as an approximation, so the value may not be saved exactly. For example, seemingly simple values like 0.1 or 0.01 may have slight errors when converted internally to binary.

This minute error is not uncommonly the cause of bugs in comparison operations or conditional statements. Therefore, it is important to choose between other numeric types depending on the use case (this will be discussed later).

2. Caution Required for Comparison Operations

For example, the following SQL statement may not work as intended.

SELECT * FROM prices WHERE amount = 0.1;

The 0.1 stored in FLOAT type may actually be slightly off like 0.10000000149011612, so exact match with = may not be obtained. This can lead to problems such as unexpected data not being retrieved.

3. Not Suitable for Scenarios Requiring High Precision

In finance, accounting, taxes, billing processing, etc., there are cases where even an error of 1 yen or 1 cent is not allowed. In such cases, the use of fixed-point types such as DECIMAL is recommended.

6. Comparison of FLOAT Type with Other Numeric Types

Selection of Numeric Types is Determined by “Precision and Usage”

MySQL provides data types such as DOUBLE and DECIMAL for handling numbers, in addition to FLOAT. All of them can handle decimals, but the choices vary greatly depending on purpose, precision, and performance.

In this chapter, we will compare the differences between the FLOAT type and other representative numeric types from specific perspectives.

FLOAT Type vs DOUBLE Type

AspectFLOAT TypeDOUBLE Type
PrecisionApprox. 7 digits (single precision)Approx. 15-16 digits (double precision)
Storage Size4 bytes8 bytes
Processing SpeedFast (lightweight)Slightly slower (precision prioritized)
UsageApproximate values, when strict precision is not requiredScientific calculations requiring high precision, etc.

The DOUBLE type can also be considered an upward compatible version of the FLOAT type. It ensures higher precision while allowing representation of a wide range of values.

For example, it is suitable for astronomical calculations or precise numerical processing other than finance. However, since storage and performance costs increase, it is necessary to use them appropriately according to the purpose.

FLOAT Type vs DECIMAL Type

AspectFLOAT TypeDECIMAL Type
PrecisionApproximate value (with error)Exact fixed-point
Storage Size4 bytes (variable)Varies by D or M (somewhat larger)
Main UsageData where approximation is acceptableAmounts, billing, taxes, precise statistics
Occurrence of ErrorOccurs (floating-point error)Does not occur (strict calculation)

The DECIMAL type, being capable of strict calculations based on decimal numbers, is recommended for situations where accuracy is emphasized, such as amounts, transaction quantities, tax rates, etc..

On the other hand, FLOAT is premised on approximate value processing with emphasis on performance, and the two are types with clearly different purposes.

How to Choose the Appropriate Numeric Type

Guidelines for selection according to usage are as follows:

  • FLOAT Type: Sensor values, measurement data, statistical processing, etc., in situations where a certain degree of error is acceptable.
  • DOUBLE Type: When higher precision calculations are needed (e.g., scientific and technical calculations or analysis processing).
  • DECIMAL Type: All calculations related to finance and billing where errors are not allowed.

If you make the wrong choice, errors can accumulate and lead to serious calculation mistakes. In processing where precision is required, there are many cases where a level of caution such as “basically do not use FLOAT” is demanded.

7. Usage Examples and Best Practices for FLOAT Type

Cases Where FLOAT Type is Actually Used

MySQL’sFLOAT type is widely used in applications where “performance is prioritized over precision” due to its characteristics. The following are representative usage examples.

1. Recording Sensor Values (IoT or Monitoring)

Sensor values such as temperature, humidity, and atmospheric pressure are suitable for the FLOAT type because recording trends in changes is more important than absolute precision.

CREATE TABLE sensor_logs (
  temperature FLOAT,
  humidity FLOAT,
  recorded_at DATETIME
);

In such applications, the FLOAT type is practical because it can process records exceeding millions at high speed.

2. Numerical Coordinates in Games or 3D Applications

The FLOAT type is also used in game development and graphics processing, where coordinates and rotation angles are handled. These data are for internal processing, and a certain amount of error is tolerable.

3. Intermediate Results in Statistical Data or Machine Learning

In statistical processing or intermediate results of AI learning, FLOAT may be used in situations where computational cost needs to be reduced. Since subsequent processing assumes normalization and correction, a small amount of error is not an issue.

Cases to Avoid Using

On the other hand, there are clearly cases where the FLOAT type should not be used.

  • Precise calculations such as amounts, fees, tax rates, etc.
  • Precise multiplication of unit prices or aggregation
  • Values recorded on invoices or receipts

For example, the following table definition is extremely dangerous:

-- Incorrect usage example
CREATE TABLE invoices (
  amount FLOAT
);

In such a structure, errors less than 1 yen can occur, potentially causing situations where the billed amount and paid amount do not match. For this, types that guarantee precision, such as DECIMAL(10,2), should be used.

Best Practices for Safely Using the FLOAT Type

  1. Use only in situations where “error is not an issue”
  • Limit to data such as physical sensor information or logs where approximate values are sufficient.
  1. Avoid equality comparisons (=)
  • Avoid comparisons like value = 0.1, and instead use range comparisons.
   WHERE value BETWEEN 0.0999 AND 0.1001
  1. Do not neglect to compare and consider other types according to the purpose
  • Make the selection criteria clear based on whether the recording target is “values handled by humans” or “mechanical fluctuation records”.
  1. Check the MySQL version and operating environment
  • In some environments, there may be differences in rounding processing or numerical comparisons, so pre-verification is essential.

8. Common Misconceptions and Troubleshooting

Misconception ① “FLOAT Type Can Perform Accurate Calculations”

The most common misconception among many developers is the assumption that “Even with FLOAT type, 0.1 + 0.2 = 0.3 works correctly”.

In reality, since the FLOAT type internally handles approximate values in binary, it may not match exactly.

SELECT 0.1 + 0.2 = 0.3; -- The result may be FALSE

Cause:

  • Because 0.1, 0.2, and 0.3 cannot be represented exactly as binary numbers on a computer, resulting in subtle errors.

Solution:

  • When comparing calculation results with FLOAT type, use comparisons that account for a tolerance for errors.
SELECT ABS((0.1 + 0.2) - 0.3) < 0.00001;

Misconception ② “Specifying FLOAT(M,D) Guarantees Precision”

Specifying the number of digits explicitly, like FLOAT(7,4), leads to many cases where people assume it will be stored exactly as specified. In reality, FLOAT type is treated merely as an “approximate value,” and errors cannot be avoided even with M or D specifications. This is a major difference from the DECIMAL type. Solution:

  • In situations where precision is important, use the DECIMAL type.

Misconception ③ “Comparison Operations (=, <, >) Can Be Used Normally”

Consultations about conditional statements like WHERE value = 0.1 not working as intended are very common. Cause:

  • Due to floating-point errors, comparison operations may not return TRUE.

Solution:

  • Perform comparisons using ranges, or store values in DECIMAL and compare accurately.

Misconception ④ “FLOAT Type Is Higher Performance and More Versatile Than DECIMAL”

Indeed, FLOAT type is fast and lightweight, but that is performance obtained at the expense of precision. For data like amounts, quantities, or balances where deviations must not occur, it is unsuitable. Solution:

  • Clearly define system requirements (precision vs. processing performance) and use FLOAT type and DECIMAL type appropriately.

Summary of Common Issues and Solutions

IssueCauseRecommended Solution
Calculation results do not matchFloating-point errorComparison with error tolerance
Does not match conditions= comparison mismatchUse BETWEEN or error comparison
Decimals are being roundedPrecision limitsProcess precise numbers with DECIMAL
Errors occur in amountsFloating-point processingDo not use FLOAT for financial processing

9. Summary

What Kind of Type is the FLOAT Type?

MySQL’s FLOAT type is a floating-point type for storing and processing approximate decimal values. While it offers the advantage of handling a wide range of values with minimal storage, it comes with limitations in precision and risks of errors, so it requires a clear purpose and thorough understanding for effective use.

Main Points Covered in This Article

  • Basics of the FLOAT Type: Handles floating-point numbers with approximately 7 significant digits.
  • Precision and Errors: There may be slight errors in values after the decimal point, so exercise caution with comparison operations.
  • Syntax and Usage: You can specify the number of digits with FLOAT(M,D), and also use UNSIGNED and ZEROFILL.
  • Comparison with Other Numeric Types:
  • DOUBLE offers higher precision.
  • DECIMAL is suitable for exact numeric calculations without errors.
  • Appropriate Use Cases: Scenarios where errors are tolerable, such as sensor data or statistical values.
  • Scenes to Avoid: Processes where accuracy is essential, such as amounts, billing, and tax calculations.
  • Common Misconceptions and Solutions: Causes of failures in comparisons like = 0.1, and using conditional expressions that account for errors as a solution, etc.

If You’re Unsure Whether to Use the FLOAT Type?

Finally, here’s a simple criterion for when you’re unsure about your decision.

Can a small error be tolerated?
YES → FLOAT type or DOUBLE type
NO → DECIMAL type

The answer to this question directly leads to the optimal choice of numeric type.

Correct Choices Build Reliability

In database design, the selection of numeric types is often overlooked, but it can easily become a breeding ground for future issues and bugs. Properly understanding the FLOAT type and using it masterfully in appropriate situations leads to stable system operations and reliable data processing.

I hope this article serves as a helpful aid in your MySQL design and operations.

Frequently Asked Questions (FAQ)

Q1. What is the difference between FLOAT and DOUBLE types?

A.The FLOAT type is the single-precision floating-point type, which can handle approximately 7 significant digits. On the other hand, the DOUBLE type is the double-precision floating-point type, offering approximately 15-16 digits of precision.
In cases where precision is important, DOUBLE is generally used, while FLOAT is preferred when prioritizing storage or processing speed.

Q2. What do M and D mean in FLOAT(M,D)?

A.M represents the total number of digits (integer part + decimal part), and D represents the number of digits in the decimal part. For example, if defined as FLOAT(7,4), 4 out of the 7 digits are allocated after the decimal point.
However, note that this is merely a guideline for the display format and does not guarantee precision.

Q3. Is it okay to use the FLOAT type for precise values like amounts of money?

A.It is not recommended. The FLOAT type stores approximate values and there is a possibility of errors occurring, making it unsuitable for handling precise amounts to the 1-yen unit.
In such cases, you should use the DECIMAL type.

Q4. Why don’t FLOAT type values match in comparison operations (=)?

A.The FLOAT type is stored internally as an approximate value, so for example, the value 0.1 may not be recorded in a completely exact form. As a result, comparisons like = 0.1 may return FALSE. As a countermeasure, it is recommended to perform range comparisons that account for errors.

Q5. Is there a way to avoid rounding errors even when using FLOAT type?

A.Unfortunately, as long as you use the FLOAT type, you cannot completely avoid rounding errors. If precision is important, the most reliable method is to avoid using FLOAT altogether and use the DECIMAL type instead.

Q6. Why is the FLOAT type provided in MySQL?

A.The FLOAT type has a significant advantage in that it can handle numerical values quickly with less storage. It is very useful in cases where errors are tolerable (e.g., sensor data, statistical logs, 3D coordinates, etc.). By limiting its use to appropriate purposes, you can improve the system’s performance