Selecting a float in MySQL

后端 未结 8 2042
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:35

I am trying to do a SELECT match on a table based upon an identifier and a price, such as:

SELECT * FROM `table` WHERE `ident`=\'ident23\' AND `         


        
相关标签:
8条回答
  • 2020-11-29 08:37

    Don't ever use floats for money.

    0 讨论(0)
  • 2020-11-29 08:39

    I was searching for solution but finally I did it using my previous php number_format() which came in seeing @hmasif's solution.

    Use this and you'll get your float - mysql match:

    $floatmatch = number_format((float)$yourfloatvariable,5);
    

    where 5 is five strings from decimal point. e.g. 7.93643

    0 讨论(0)
  • 2020-11-29 08:44

    Try this: SELECT * FROM table WHERE price like 101.31;

    0 讨论(0)
  • 2020-11-29 08:48

    Today, I also came across the same situation and get resolved just by using FORMAT function of MySQL, It will return the results that exactly match your WHERE clause.

    SELECT * FROM yourtable WHERE FORMAT(col,2) = FORMAT(value,2)
    

    Explanation: FORMAT('col name', precision of floating point number)

    0 讨论(0)
  • 2020-11-29 08:49

    Casting to a decimal worked for me:

    SELECT * FROM table WHERE CAST(price AS DECIMAL) = CAST(101.31 AS DECIMAL);
    

    However, you may want to consider just making the price column a DECIMAL in the first place. DECIMAL is generally considered to be the best type to use when dealing with monetary values.

    0 讨论(0)
  • 2020-11-29 08:51

    Does this work?

    SELECT * , ROUND( price, 2 ) rounded
    FROM table
    WHERE ident = 'ident23'
    HAVING rounded = 101.31
    
    0 讨论(0)
提交回复
热议问题