Remove trailing zeros in decimal value with changing length

前端 未结 15 2811
醉话见心
醉话见心 2020-12-05 04:36

I have a procedure I am doing that displays odds but the client wants only significant digits to be shown. So, 1.50 would show as \'1.5\' and 1.00 would show as \'1\'.

相关标签:
15条回答
  • 2020-12-05 05:07

    If you are using PHP as the scripting language you may use the following:

    $var = (float)$var_having_extra_0; // $var = (float) 17.5000
    

    Or use the PHP floatval function:

    $var = floatval($var_having_extra_0); // $var = floatval(17.5000)
    
    0 讨论(0)
  • 2020-12-05 05:09

    To remove trailing zeros from a DECIMAL/NUMERIC or string type column, you can simply cast the value to DOUBLE, e.g.:

    SELECT CAST(mycol AS DOUBLE) from mytable;
    

    In fact, the "add zero" trick mentioned in other answers does the same, but in a more indirect (and likely less efficient) way, e.g:

    SELECT CAST(mycol AS CHAR)+0 FROM mytable; -- converts to string, then to number
    SELECT TRIM(mycol)+0 FROM mytable; -- ditto
    
    0 讨论(0)
  • 2020-12-05 05:15
    SELECT TRIM(TRAILING '0' FROM yourodds)
    FROM ...
    

    Docs for the TRIM function.

    0 讨论(0)
  • 2020-12-05 05:16

    this worked for me.. round the field to 2 decimal places and then trim any trailing zeros

    So that 2.10 is 2.1

    SELECT trim(round(FIELDNAME,2))+0 
    FROM tbl_name
    ....
    
    0 讨论(0)
  • 2020-12-05 05:18

    Taking forward the answer provided by @fooquency, if the column is already declared as a DECIMAL with a non-zero value for D in DECIMAL(M, D), we do not need to perform the WHERE condition

    WHERE yourfield LIKE '%.%'
    

    as the values in the column will always contain D digits after the decimal dot (.)

    0 讨论(0)
  • 2020-12-05 05:19

    The best solution I found is to cast your round value to FLOAT:

    SELECT CAST(ROUND(1.2345984372, 2) AS FLOAT)
    
    0 讨论(0)
提交回复
热议问题