Search code examples
mysqlfloating-point-precision

SELECT a FLOAT with given precision


I want to store my values as FLOATS, but when retrieving them the user can specify (and change at runtime) how many digits he wants to see after the decimal point.

Can I pass that in my SELECT somehow, or do I have to do it in my application?


Solution

  • Yes, just specify the second parameter for ROUND()

    SELECT ROUND(23.298, <precision>);
    

    With this, you can specify the number of digits you would like to get returned. (you can even have negative values, in wither case, the input gets rounded to 10(-precision)).

    Or you could use CAST as DECIMAL:

     CAST(2.5 AS DECIMAL(20,2))
    

    (Note: this latter would work with textual inputs too, like CAST('2.5' AS DECIMAL(20,2)), but in this case it is about FLOAT inputs)