[英]MySQL ROUND with column for decimals not working as expected when inside CONCAT
I encountered an issue where I was not getting the expected number of decimal places output when using the ROUND()
function within a CONCAT()
function. 我在使用
CONCAT()
函数中的ROUND()
函数时没有得到期望的小数位数输出的问题。
I simplified and reproduced the issue in this SQL Fiddle 我在此SQL Fiddle中简化并重现了该问题
Sample database creation and data entry code (from sqlfiddle): 示例数据库创建和数据输入代码(来自sqlfiddle):
CREATE TABLE `test` ( `Amount` DECIMAL(10,5) NOT NULL , `Decimals` SMALLINT(6) NOT NULL ) ENGINE = InnoDB;
INSERT INTO test (Amount, Decimals) VALUES
(100.12345, 1),
(100.12345, 2),
(100.12345, 3);
Query to reproduce the problem: 重现该问题的查询:
SELECT CONCAT(ROUND(`Amount`, Decimals), ' ') FROM test
All of the rows are output with 5 decimal places. 所有行的输出均以5位小数位表示。
This query produces the correct results: 此查询产生正确的结果:
SELECT ROUND(`Amount`, Decimals) FROM test
I think I've found a bug? 我想我发现了一个错误? If so, is there any other workaround I can use in the meantime that will work correctly?
如果是这样,在此期间我还能使用其他解决方法吗? In my real world example, I need to concatenate the meter readings rounded to the specified decimals with the text for the unit (eg hours, miles).
在我的实际示例中,我需要将四舍五入到指定小数点的仪表读数与单位文本(例如小时,英里)连接起来。 My actual SQL for that part looks like this:
我对该部分的实际SQL如下所示:
CONCAT(ROUND(`MeterInstances`.`Reading`, `Meters`.`DecimalPlaces`), ' ', `Meters`.`Units`)
I don't think it's really a bug. 我不认为这确实是一个错误。 CONCAT just returns the length of the decimal part of the variable
Amount
, which is 5. (the variable is 10,5). CONCAT只是返回变量
Amount
的小数部分的长度,即5。(变量为10,5)。
What you can do is use the SUBSTRING function to cut off the unnecessary decimal parts, like this: 您可以做的是使用SUBSTRING函数截去不必要的小数部分,如下所示:
SELECT CONCAT(SUBSTRING(ROUND(`Amount`, Decimals), 1, LENGTH(`Amount`)-5+`Decimals`), ' ') FROM test
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.