MySQL round half

后端 未结 4 1053
时光取名叫无心
时光取名叫无心 2021-01-23 14:27

Is it possible, in MySQL, to round half a specific way like PHP would do?

  • PHP_ROUND_HALF_UP
  • PHP_ROUND_HALF_DOWN
  • P
4条回答
  •  -上瘾入骨i
    2021-01-23 14:48

    There has been a bug in the ROUND() function in MySQL for quite some time where it returns inconsistent results depending on whether it considers the input value it is rounding an exact or approximate number. There are at least a couple of bugs logged on this (see here as well as MySQL 5.7 description of the behavour here).

    I experienced the issue with MySQL 5.6.22 but it appears to be quite pervasive judging by some of the discussion dating back to 2001. It appears to have been fixed in late 2017 early 2018 but I cannot attest as to which versions work correctly and which don't.

    The following is a workaround that will allow you to round to one decimal place with consistent results regardless whether is treated by MySQL as an exact or approximate number:

    SELECT ROUND(CAST( AS DECIMAL(10,2)), 1)
    

    If you need to round to more round places, change the second parameter to ROUND() from 1 to the number of decimal places you need and the second parameter to DECIMAL() from 2 to a value one higher than the number of decimal places you need. E.g. for 3 decimal places you could use:

    SELECT ROUND(CAST( AS DECIMAL(10,4)), 3)
    

    Note that the first parameter for DECIMAL() is the total number of digits in the number so, if you need to store large values, you may need to adjust that accordingly. For more details see the MySQL manual.

提交回复
热议问题