Friday, December 5, 2008

Decimal Calculation in SQL Server

In Arithmetic calculations some developers may struggling in getting the results with specified decimals digits.
Say for Example when the user executes the below query
SELECT 1/12
The result of the query is 0
The expected result for the user is 0.08
ie., The user wants the results with two decimal points.
Solution:
The following steps will give you the expected results
Step 1: Convert/Cast the value 1 to float type
Step 2: Round off the full value ie., 1/12 to two digits
Step 1 Execution:
SELECT CAST(1 AS FLOAT)/12
The output for the above query is 0.0833333333333333

Step 2 Execution :
SELECT ROUND(CAST(1 AS FLOAT)/12,2)
The output for the above query is 0.08 as the user expected.

2 comments:

Unknown said...

I hope the same can be achieved through
select 1/12.0

Correct me if i am wrong

Thiyagarajan said...

Yeah we can do that... But in the developement we cannot hard code the zero with the value (Like 12.0). Instead of that we can use some casting for the value 12 also.