How to get float or decimal result while dividing integers in SQL Server?

In SQL Server when you divide an integer with another integer, the result will always be an integer. The fractional part of the resultant value is truncated, and only the whole number portion is returned. In order to get float or decimal results while dividing integers in SQL Server, you have to cast or convert one of the integers to a float or decimal before performing the division.

For example, when you divide 7 by 3, the result will be 2, as the fractional part (0.33333) is truncated.

Dividing integers in SQL Server gives integer result.

Using the above example SQL statement, let’s cast @Integer_A to a float and then to a decimal and see the result:

DECLARE @Integer_A INT, 
	@Integer_B INT;

SET @Integer_A = 7;
SET @Integer_B = 3;

SELECT CAST(@Integer_A AS float) / @Integer_B AS Result_Float;

SELECT CAST(@Integer_A AS decimal) / @Integer_B AS Result_Decimal;
Get float or decimal result while dividing integers in SQL Server

Now, you will get the actual result without truncation. So, to get a float or decimal result while dividing integers, use cast or convert one of the integers to a float or decimal before performing the division.

Related Articles

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.