How to get second argument of Round() to work with columns?

馋奶兔 提交于 2020-01-16 04:13:10

问题


I've a simple table with an integer column:

# setup table:
create table t(x int); insert t select 1;

The query select round(1.234, 1) from t returns 1.2 as expected.

However, select round(1.234, x) from t returns 1.2000. (It should return 1.2, as per the docs.)

Is this a bug? (Tested on version 5.5.10 and latest 5.6.24.)

Or, is there any particular technical reason why columns cannot be used in the second argument of round?

How can we get round to work even while there are columns used in the second argument?


回答1:


Consider using FORMAT instead of ROUND:

mysql> SELECT FORMAT(1.234, x) FROM ( SELECT 1 AS x ) y;
+------------------+
| FORMAT(1.234, x) |
+------------------+
| 1.2              |
+------------------+

If that is not satisfactory, file a bug about ROUND.




回答2:


This bug is not restricted to ROUND(), but also happens for TRUNCATE().

The accepted answer/workaround from @RickJames is not entirely correct, since FORMAT() introduces thousand separators: FORMAT() documentation

Correct workaround for arbitrary values:

SELECT REPLACE(FORMAT(t.raw_number, t.decimal_places), ',', '')
FROM   my_table t;

(Adding my comment as separate answer, since I do not have enough points to comment...)



来源:https://stackoverflow.com/questions/29912352/how-to-get-second-argument-of-round-to-work-with-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!