Round *UP* to the nearest 100 in SQL Server

后端 未结 13 956
野性不改
野性不改 2020-12-25 11:18

Is it possible to easily round a figure up to the nearest 100 (or 1000, 500, 200 etc.) in SQL Server?

So:

720 -> 800
790 -> 800
1401 -> 1500

相关标签:
13条回答
  • 2020-12-25 11:38

    It is very simple to round a number to any multiple of nearest 10 by using simply the ROUND function for ex:

    SELECT ROUND(number/1000,2)*1000 
    

    This will give you the nearest thousandth value.

    0 讨论(0)
  • 2020-12-25 11:38

    There's no native function that will do this, but there are any number of simple math tricks that will. An example:

    DECLARE @Foo int
    SET @Foo = 720
    
    print @Foo
    print (@Foo + 100) % 100
    PRINT @Foo - (@Foo + 100) % 100
    
    0 讨论(0)
  • 2020-12-25 11:39

    The following should work. After reading your question, I'm not exactly sure what you want 100 to return. For this 100 returns 100.

    select floor((X + 99) / 100) * 100;
    

    This gives the following results:

    0 -> 0
    1 -> 100
    99 -> 100
    100 -> 100
    101 -> 200
    
    0 讨论(0)
  • 2020-12-25 11:40

    Try this:

    select round(@value , -2);

    0 讨论(0)
  • 2020-12-25 11:48

    Use CEILING function to round a figure up

    DECLARE @Number DECIMAL, @RoundUp DECIMAL
    SET @RoundUp = 100
    SET @Number = 720
    SELECT CEILING(@Number/@RoundUp)*@RoundUp
    
    0 讨论(0)
  • 2020-12-25 11:50

    It works fine for integer value:

    @roundUpValue = ((@intValue / 1000) + 1) * 1000
    @roundDownValue = (@intValue / 1000) * 1000
    

    For example

    declare @intValue as int = 1934
    select ((@intValue / 1000) + 1) * 1000 as roundUp
    select (@intValue / 1000) * 1000 as roundDown
    

    If you want to round up to the nearest 500 then

    select ((@intValue / 500) + 1) * 500 as roundUp
    
    0 讨论(0)
提交回复
热议问题