有没有办法将数字转换为具有指定小数位数的小数?我试过了:
SELECT ...
CAST(NumericField AS NUMERIC(15, @DecimalPlaces) AS NumericField,
...
但它不起作用。
编辑:我犯了一个错误并写了NUMBER
而不是NUMERIC
。但问题仍然存在:如何使用指定的小数位数转换为NUMERIC
?
答案 0 :(得分:3)
declare @Value float = 123.4567, @RoundTo int = 2
select round(@Value * power(10, @RoundTo), 0) / power(10, @RoundTo)

答案 1 :(得分:2)
declare @decimal int=5
declare @decimalNum float =8931.0380106023125083
select ROUND(@decimalNum, @decimal,1)
对于尾随零,请使用:
declare @decimal int=5
declare @decimalNum float =8931.12
select STR(@decimalNum, 25, @decimal)
请注意,上面的select将返回varchar类型,而不是decimal,numeric,float或任何其他类型。
答案 2 :(得分:1)
您想要转换为十进制而不是数字..
cast(值为十进制(10,2))10是包含小数的总数,2是小数位数
答案 3 :(得分:1)
单程......
WITH T(NumericField, DecimalPlaces) AS
(
SELECT 1.234,10 UNION ALL
SELECT 1.234,3
)
SELECT CASE DecimalPlaces
WHEN 15 THEN CAST(NumericField AS NUMERIC(30, 15))
WHEN 14 THEN CAST(NumericField AS NUMERIC(30, 14))
WHEN 13 THEN CAST(NumericField AS NUMERIC(30, 13))
WHEN 12 THEN CAST(NumericField AS NUMERIC(30, 12))
WHEN 11 THEN CAST(NumericField AS NUMERIC(30, 11))
WHEN 10 THEN CAST(NumericField AS NUMERIC(30, 10))
WHEN 09 THEN CAST(NumericField AS NUMERIC(30, 9))
WHEN 08 THEN CAST(NumericField AS NUMERIC(30, 8))
WHEN 07 THEN CAST(NumericField AS NUMERIC(30, 7))
WHEN 06 THEN CAST(NumericField AS NUMERIC(30, 6))
WHEN 05 THEN CAST(NumericField AS NUMERIC(30, 5))
WHEN 04 THEN CAST(NumericField AS NUMERIC(30, 4))
WHEN 03 THEN CAST(NumericField AS NUMERIC(30, 3))
WHEN 02 THEN CAST(NumericField AS NUMERIC(30, 2))
WHEN 01 THEN CAST(NumericField AS NUMERIC(30, 1))
WHEN 00 THEN CAST(NumericField AS NUMERIC(30, 0))
ELSE CAST(NULL AS SQL_VARIANT)
END
FROM T
答案 4 :(得分:1)
也许你可以试试这个: DECLARE @quantityPrecision INT = 5; 设置@quantityPrecision = yourvalue 更新表A. 设定数量=圆(数量,@ quantityPrecision) 其中XXX