Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

php - MySQL round weird bug

I'm facing a really weird ?bug? on mysql+php right now. Is a simple select, in the following example i'm using multiple fields to try to explain my problem:

  • "field" is 11.5
  • $phpvar is 1.15

MySQL query:

select round(field * " . $phpvar . " ,2) as a1, 
       round(field * 1.15 ,2) as a2, 
       round(11.5 * " . $phpvar . " ,2) as a3, 
       round(11.5 * 1.15 ,2) as a4, 
       field * " . $phpvar . " as a5 
from ...

ok, i'm trying to get 13.23. "field" * $phpvar = 13.225, so using round(13.225,2) I should get 13.23, right? well, yes and no.

query results:

  • a1 [round(field * " . $phpvar . " ,2)] => 13.22
  • a2 [round(field * 1.15 ,2)] => 13.22
  • a3 [round(11.5 * " . $phpvar . " ,2)] => 13.23
  • a4 [round(11.5 * 1.15 ,2)] => 13.23
  • a5 [field * " . $phpvar . "] => 13.225 (without round)

what am I missing? how is it possible, when it comes to use "field", my result gets a fake round?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is how the DOUBLE and FLOAT values are stored.

It is possible (and probable) that values like 11.5 or 22.475 coul be stored in approximated values like 11.499999999999~ or 22.475000000000000001 thus some calculations or roundings could lead to incorrect results.

It is always better to store float values into a DECIMAL coulmn type where the value is stored exactly with all the decimal digits and is not approximated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...