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

2019-08-01 14:55发布

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?

2条回答
女痞
2楼-- · 2019-08-01 15:52

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.

查看更多
Fickle 薄情
3楼-- · 2019-08-01 16:00

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...)

查看更多
登录 后发表回答