How to Round numbers in database to two decimal places using a MySql query

前端 未结 2 1288
感动是毒
感动是毒 2021-01-14 06:45

I want to round the numbers to 2 decimal points in a woo commerce database table wp_postmeta. There is a column \'meta_key\' with row \'_pric

相关标签:
2条回答
  • 2021-01-14 07:08

    You can round your column with Round Function , Use function like this :

    SELECT ROUND(column_name,decimals) FROM table_name; 
    

    in this case write query like below :

    select Round(_Price , 2) from your table name
    
    0 讨论(0)
  • 2021-01-14 07:11

    The documentation on round says:

    ROUND(X), ROUND(X,D)

    Rounds the argument X to D decimal places. [...] D defaults to 0 if not specified.

    So your update would be:

    UPDATE wp_postmeta 
    SET    meta_value = ROUND(meta_value, 2)
    WHERE  meta_key='_price'
    

    Display formats

    If your concern is to display a number with 2 decimal digits, it might be better to keep the complete precision as it is, but change the way you select values from your table, and us format:

    Without the above update, you can still do this:

    SELECT FORMAT(meta_value, 2)
    FROM   wp_postmeta
    WHERE  meta_key='_price'
    

    If in your table you have the value 15.002916 then the above select will render it to a string: 15.00.

    Finally, if the data type of meta_value is a varchar (so, not a numerical data type), you can of course store the additional trailing zeroes:

    UPDATE wp_postmeta 
    SET    meta_value = FORMAT(meta_value, 2)
    WHERE  meta_key='_price'
    

    But do realise that this only works as expected if the data type is of the text kind. In numerical data types the values 15.00 and 15 are exactly the same; it is just their display format which is different.

    0 讨论(0)
提交回复
热议问题