例如,我有一个下表
x double
d tinyint
对于不同的值,我想呈现不同的精度,例如
select round(x,d);
有人对此有很好的解决方案吗?存储过程或与精度有关的东西保存在与值相同的表中。
请注意,如果 round(X, D) 中的 D 是一列,您将不会得到预期的结果。
如果您尝试以下操作:
USE test;
DROP TABLE IF EXISTS test_tbl;
CREATE TABLE test_tbl (x double, d tinyint) ENGINE MyISAM;
INSERT IGNORE INTO test_tbl (x,d) VALUES (1.12,3),(1.1234,3);
SELECT x,d,round(x,3),round(x,d) FROM test_tbl;
结果将是:
x d round(x,3) round(x,d)
1.12 3 1.120 1.12
1.1234 3 1.123 1.123
注意第一轮(x,d)不是1.120,它会显示为1.12!
更新的解决方案
如果您定义如下所述的函数,您将获得预期的结果。
DELIMITER $$
DROP FUNCTION IF EXISTS StrRound;
CREATE FUNCTION StrRound(x double, d tinyint) RETURNS varchar(16) DETERMINISTIC COMMENT 'Returns string where x is rounded to d decimals (d from -6 to 6)'
BEGIN
DECLARE s varchar(16);
IF d=0 THEN SET s=cast(round(x, 0) as char);
ELSEIF d=1 THEN SET s=cast(round(x, 1) as char);
ELSEIF d=2 THEN SET s=cast(round(x, 2) as char);
ELSEIF d=3 THEN SET s=cast(round(x, 3) as char);
ELSEIF d=4 THEN SET s=cast(round(x, 4) as char);
ELSEIF d=5 THEN SET s=cast(round(x, 5) as char);
ELSEIF d=6 THEN SET s=cast(round(x, 6) as char);
ELSEIF d=-1 THEN SET s=cast(round(x, -1) as char);
ELSEIF d=-2 THEN SET s=cast(round(x, -2) as char);
ELSEIF d=-3 THEN SET s=cast(round(x, -3) as char);
ELSEIF d=-4 THEN SET s=cast(round(x, -4) as char);
ELSEIF d=-5 THEN SET s=cast(round(x, -5) as char);
ELSEIF d=-6 THEN SET s=cast(round(x, -6) as char);
ELSE SET s=cast(x as char);
END IF;
RETURN s;
END;$$
DELIMITER ;