问题
So I'm running MySQL version 5.1.4 and I'm trying to select distinct by a rounded value, and it works great except that it rounds numbers like 12.5 to 12 instead of 13. The columns I have tried this on have all been type double. I did a bit of research and saw the default behavior is to round half up so I'm wondering if there is some setting or parameter I need to change or if this is just broken?
Here is my query for reference :
SELECT DISTINCT ROUND(radius) as radius FROM arch
WHERE radius != '' ORDER BY radius
ASC
回答1:
See this. Converting the radius
column to DECIMAL
should solve the problem.
回答2:
http://dev.mysql.com/doc/refman/5.1/en/precision-math-rounding.html
The half round rule only applies to exact numbers (i.e. Integers and Decimals), for you Doubles the behavior depends on the underlying C library.
I suspect you are going to have to convert the values to DECIMAL to get the desired rounding.
回答3:
In MySQL for exact value types (DECIMAL, INT) employs half up rounding (so 12.5
rounds to 13
).
For approximate types (FLOAT, DOUBLE), MySQL will typically use round half even aka bankers rounding (12.5
rounds to 12
, while 13.5
rounds to 14
).
To get around this, you could add 0.5
to the number before you round, or convert your approximate value type to DECIMAL.
回答4:
SELECT DISTINCT ROUND(radius+0.1) as radius FROM arch WHERE radius != '' ORDER BY radius ASC
Perhaps reduce the modifier further if needed.
回答5:
What you want is CEILING http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
SELECT DISTINCT CEILING(radius) as radius FROM arch WHERE radius != '' ORDER BY radius ASC
来源:https://stackoverflow.com/questions/9913109/mysql-round-function-using-round-half-down-instead-of-half-up