简体   繁体   中英

sql server round

select round((cast(56/3 AS DECIMAL (4,2))),1)

is showing 18 output instead of 19 , where as actual value is 18.66. My Round function is not working please help.

The problem is 56/3 is an integer calculation which means no floating point numbers.

You need to use floating point numbers in the initial calculation eg 56.0/3 . Also, if you want to round to 19 then you need to round to the nearest whole number, ROUND(x, 1) will round to the first decimal place - you need to pass 0 to round up to 19.

SELECT ROUND((CAST(56.0/3 AS DECIMAL (4,2))),0)

Alternatively, you could switch ROUND for CEILING

select CEILING(CAST(56.0/3 AS DECIMAL(4,2)))

Your section of the code:

CAST( 56/3 AS DECIMAL )

First evaluates the 56/3 which returns 18. This is then cast to decimal, giving 18.0.

You need to cast either the numerator or denominator before the division occurs.

The round function is working fine -- it's just not using the input you think it is.

Convert one of your integer values before you divide the numbers:

select round(56/convert(DECIMAL (4,2),3),0);

If you do not so you divide integers which results in 18 not 18.66

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