Cast into a decimal with a specified amount of decimal places
Is there any way to cast a number into a decimal with a specified number of decimal places? I tried开发者_开发百科:
SELECT ...
CAST(NumericField AS NUMERIC(15, @DecimalPlaces) AS NumericField,
...
But it didn't work.
EDIT: I made a mistake and wrote NUMBER
instead of NUMERIC
. But the question stands still: How do I cast to a NUMERIC
with a specified number of decimal places?
declare @Value float = 123.4567, @RoundTo int = 2
select round(@Value * power(10, @RoundTo), 0) / power(10, @RoundTo)
declare @decimal int=5
declare @decimalNum float =8931.0380106023125083
select ROUND(@decimalNum, @decimal,1)
For trailing zeros use this:
declare @decimal int=5
declare @decimalNum float =8931.12
select STR(@decimalNum, 25, @decimal)
Please note, the above select will return a varchar type, not decimal, numeric, float or any other types.
One way...
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
You want to cast as decimal instead of a number..
cast(value as decimal(10,2)) 10 is the total numbers including the decimals and 2 is the number of decimals
maybe you can try this : DECLARE @quantityPrecision INT=5; set @quantityPrecision = yourvalue update tableA set quantity = round(quantity,@quantityPrecision) where XXX
精彩评论