Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 237
pyon Avatar asked Dec 27 '22 20:12

pyon


2 Answers

declare @Value float = 123.4567, @RoundTo int = 2
select round(@Value * power(10, @RoundTo), 0) / power(10, @RoundTo)
like image 170
Irawan Soetomo Avatar answered May 03 '23 04:05

Irawan Soetomo


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.

like image 32
Dimitri Avatar answered May 03 '23 04:05

Dimitri