Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing 2 float values in sqlserver

Tags:

sql-server

I have a float variable-field1 in 2 tables-table1 & table2. When I query the table and check the values of the field both look identical but when I find their difference it gives a difference instead of zero.

Field1(Table1) value---84.4660194174757
Field2(Table2) value---84.4660194174757

Differnce---1.4210854715202E-14

Why would I get this problem?

like image 591
user1050619 Avatar asked Apr 22 '13 14:04

user1050619


People also ask

Can we use == to compare two float values?

Yes if they are Float objects.

How do you compare two float values?

The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Parameters: The function accepts two parameters: f1: The first float value to be compared.

How do I compare two decimal values in SQL?

Hence, this is equivalent to: declare @num1 decimal(18, 0) = 1.98; declare @num2 decimal(18, 0) = 2.2; SQL Server then assigns the values by converting the constants to the appropriate value, and both are being set to "2.". You need to explicitly set the precision/scale if you want those values to be stored exactly.

How do you compare variables in SQL?

You can easily compare variables using INTERSECT as it is NULL -sensitive: DECLARE @A BIT = NULL ,@B BIT = 1; IF EXISTS ( SELECT @A INTERSECT SELECT @B ) SELECT 'equal'; ELSE SELECT 'not equal'; Also, when you need to do such comparisons in complex queries, this could improve performance as it allows using indexes.


1 Answers

  • Use ROUND to limit the decimal places
  • Use ABS(value1-value2) < 0.00001 with some suitable value
  • Don't use float
like image 84
gbn Avatar answered Sep 28 '22 08:09

gbn