Home > Database > Mysql Tutorial > Why Are MySQL Floating-Point Comparisons Inaccurate?

Why Are MySQL Floating-Point Comparisons Inaccurate?

Susan Sarandon
Release: 2024-11-07 12:12:02
Original
470 people have browsed it

Why Are MySQL Floating-Point Comparisons Inaccurate?

MySQL Floating Point Comparison Imperfections

While introducing floating point columns to a MySQL database schema proves useful, comparisons involving floating point values can occasionally yield unreliable outcomes.

To demonstrate:

Consider a table with a points column containing the following values:

1 - 50.12
2 - 34.57
3 - 12.75
4 - ...(all other values are less than 12.00)
Copy after login

Executing the query:

SELECT COUNT(*) FROM `users` WHERE `points` > "12.75"
Copy after login

unexpectedly returns "3."

It's a known fact that MySQL comparisons of floating point values are prone to inconsistencies, and that the decimal data type is a better choice for such comparisons.

Can You Continue Using the Float Type?

While it's generally recommended to use the DECIMAL data type for precise floating point comparisons, you can still proceed with the float type if you're aware of its potential pitfalls. One such pitfall is the potential for slight precision loss during calculations.

For instance, let's consider the following table:

CREATE TABLE a (num float);

INSERT INTO a VALUES (50.12);
INSERT INTO a VALUES (34.57);
INSERT INTO a VALUES (12.75);
INSERT INTO a VALUES (11.22);
INSERT INTO a VALUES (10.46);
INSERT INTO a VALUES (9.35);
INSERT INTO a VALUES (8.55);
INSERT INTO a VALUES (7.23);
INSERT INTO a VALUES (6.53);
INSERT INTO a VALUES (5.15);
INSERT INTO a VALUES (4.01);
Copy after login

Running the query:

SELECT SUM(num) FROM a;
Copy after login

yields the result:

159.94000005722
Copy after login

Note the unexpected "0.00000005722." Such rounding errors can lead to discrepancies in comparisons.

To mitigate such issues, you can convert the float columns to a DECIMAL data type with a specified precision and scale. For example:

ALTER TABLE a MODIFY num DECIMAL(6,2);

SELECT SUM(num) FROM a;
Copy after login

The result now becomes:

159.94
Copy after login

By using the DECIMAL data type, you can ensure accurate comparisons and avoid the precision issues associated with floating point values in MySQL.

The above is the detailed content of Why Are MySQL Floating-Point Comparisons Inaccurate?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template