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:48

Another truncate with no rounding solution and example.

    Convert 71.950005666 to a single decimal place number (71.9)
    1) 71.950005666 * 10.0 = 719.50005666
    2) Floor(719.50005666) = 719.0
    3) 719.0 / 10.0 = 71.9

    select Floor(71.950005666 * 10.0) / 10.0
查看更多
永恒的永恒
3楼-- · 2019-01-01 13:49

I think you want only the decimal value, in this case you can use the following:

declare @val decimal (8, 3)
SET @val = 123.456

SELECT @val - ROUND(@val,0,1)
查看更多
怪性笑人.
4楼-- · 2019-01-01 13:52

Here's the way I was able to truncate and not round:

select 100.0019-(100.0019%.001)

returns 100.0010

And your example:

select 123.456-(123.456%.001)

returns 123.450

Now if you want to get rid of the ending zero, simply cast it:

select cast((123.456-(123.456%.001)) as decimal (18,2))

returns 123.45

查看更多
与君花间醉酒
5楼-- · 2019-01-01 13:52

Mod(x,1) is the easiest way I think.

查看更多
登录 后发表回答