简体   繁体   中英

Rounding number up or down, based on 0.5 and closest to round number

I'm having trouble using CEILING and FLOOR in SQL Server .

The problem is, I want to round up based on decimal value 0.5

For example:

- 2.56 -> 3
- 1.2 -> 1
- 4.1 -> 4
- 0.7 -> 1
- 0.48 -> 0

As you can see, I need to get lower round number if decimal value is < .5 and higher round number if >= .5.

CEILING and FLOOR only round up to lowest or highest decimal value and I do not get the desired results.

Any suggestions?

I would expect round() to do what you want. But if you want to be explicit, then try:

floor(x + 0.5)

Read this ... https://sqlstudies.com/2016/10/05/floor-round-and-ceiling/

Round does a standard rounding. If value is .5 or over then you get back 1. If it's less than .5 you get back 0

Ceiling returns the integer equal to or higher than the value passed in.

    SELECT ROUND(2.56,0); 
    Answer= 3.00

    SELECT ROUND(2.56,1); 
    Answer= 2.60

    SELECT CEILING(2.56);
    Answer= 3

In case if you have requirement to change the window from 0.5 to something else, you can use this logic (Note: @number is your input)

DECLARE @Number AS DECIMAL
SET @Number = 0.49

SELECT @Number+ CASE WHEN @Number%1 BETWEEN 0.000 AND 0.249 THEN 0.000 - @Number%1
                     WHEN @Number%1 BETWEEN 0.250 AND 0.500 THEN 0.500 -@Number%1
                     WHEN @Number%1 BETWEEN 0.500 AND 0.749 THEN 0.500 -@Number%1
                     WHEN @Number%1 BETWEEN 0.750 AND 0.999 THEN 1.000 -@Number%1
                END

You can use cast

Select cast(YourX+0.5 as int);

用这个:

SELECT CAST(ROUND(CAST(0.5 AS NUMERIC(5, 2)),0) AS int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM