Truncate (not round) decimal places in SQL Server

2019-01-01 13:07发布

I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:

declare @value decimal(18,2)

set @value = 123.456

This will auto round @Value to be 123.46....which in most cases is good. However, for this project I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the left() function and convert back to a decimal...any other ways?

16条回答
旧时光的记忆
2楼-- · 2019-01-01 13:32

I know this question is really old but nobody used sub-strings to round. This as advantage the ability to round really long numbers (limit of your string in SQL server which is usually 8000 characters):

SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)
查看更多
后来的你喜欢了谁
3楼-- · 2019-01-01 13:33
SELECT Cast(Round(123.456,2,1) as decimal(18,2))
查看更多
零度萤火
4楼-- · 2019-01-01 13:38

Another way is ODBC TRUNCATE function:

DECLARE @value DECIMAL(18,3) =123.456;

SELECT @value AS val, {fn TRUNCATE(@value, 2)} AS result

LiveDemo

Output:

╔═════════╦═════════╗
║   val   ║ result  ║
╠═════════╬═════════╣
║ 123,456 ║ 123,450 ║
╚═════════╩═════════╝

Remark:

I recommend using built-in ROUND function with 3rd parameter set to 1.

查看更多
弹指情弦暗扣
5楼-- · 2019-01-01 13:40

Do you want the decimal or not?

If not, use

select ceiling(@value),floor(@value)

If you do it with 0 then do a round:

select round(@value,2)
查看更多
梦该遗忘
6楼-- · 2019-01-01 13:40
select convert(int,@value)
查看更多
牵手、夕阳
7楼-- · 2019-01-01 13:46

Please try to use this code for converting 3 decimal values after a point into 2 decimal places:

declare @val decimal (8, 2)
select @val = 123.456
select @val =  @val

select @val

The output is 123.46

查看更多
登录 后发表回答