简体   繁体   中英

Perl/mysql floating point imprecision

I'm using Perl to communicate floating point numbers with a mysql database. I perform a multiplication in perl:

 $var = 0.001 * 3;

I then store this value in a mysql database in a column of type DOUBLE. I later retrieve the result, perform a further multiplication and addition to the number and store it back into the database

$previous_result_from_db += 0.001*1 + 0.001*0.5.

The result stored in the database should be , but instead I get: . ,但我得到的是: I'm trying to understand where the source of the imprecision is. Is it Perl or the database? What is the correct way to handle this kind of floating point interaction to avoid the imprecision?

Thanks!

"10.0 times 0.1 is hardly ever 1.0" -- Brian Kernighan, The Elements of Programming Style

It is a known limitation of FLOAT and DOUBLE that they are imprecise numeric data types. This is built into the design of the IEEE 754 format. It affects all programming languages that store floating-point numbers using this format.

MySQL documents this in this appendix: B.5.5.8 Problems with Floating-Point Values .

PHP documents this in Warning: Floating point precision .

If you want a scaled numeric data type in MySQL that avoids this rounding behavior, use DECIMAL .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM