Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server compare two decimals is not exact

I am using SQL Server 2008 R2. Why is this comparison returning true? Values are 1.98 and 2.2, which is very different:

declare @num1 decimal = 1.98;
declare @num2 decimal = 2.2;

if(@num1 != @num2)
    select 0;
else if(@num1 = @num2)
    select 1;
like image 526
FrenkyB Avatar asked Apr 12 '26 00:04

FrenkyB


1 Answers

You have not included the precision and scale values in your declaration of @num1, @num2 variables. Hence, default values are being used.

According to the documentation:

Scale can be specified only if precision is specified. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.

So the scale of both variables defaults to 0 and thus both variables are being set to 2.

You can easily get around the problem by using declaration statements like:

declare @num1 decimal(10,2) = 1.98;
declare @num2 decimal(10,2) = 2.2;
like image 153
Giorgos Betsos Avatar answered Apr 14 '26 21:04

Giorgos Betsos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!