Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding issue with SQL Server and REAL datatype

I'm seeing some strange behavior when rounding in SQL Server 2008. Given the following code:

DECLARE @Value REAL
SELECT @Value = .35
SELECT ROUND(@Value, 1)

I would expect the value to be .4, however it outputs .3. I must assume this is because the value stored is actually less than .35, something like .34999999999999. Is this the case, or am I doing something wrong? Is there a way to ensure this behaves as expected, at least from the visible value?

like image 395
Brian Vallelunga Avatar asked Mar 02 '12 00:03

Brian Vallelunga


People also ask

What is real data type in SQL Server?

The REAL data type is an approximate number with floating point numeric data. REAL value is approximate which means not all range of values can be represented exactly. REAL is equivalent to FLOAT(24).

How do you round off data in SQL?

SQL Server ROUND() Function The ROUND() function rounds a number to a specified number of decimal places.

Should I use float or real?

float is used to store approximate values, not exact values. It has a precision from 1 to 53 digits. real is similar but is an IEEE standard floating point value, equivalent to float(24). Neither should be used for storing monetary values.


1 Answers

When you are using floating-point values like REAL and FLOAT (same thing), the SQL Server ROUND() function follows IEEE Standard 754 and uses the "round up" algorithm.

But that means different things for different floating-point values. Some ".5" values end up getting stored as an approximation of ".49999999999", others as ".500000001", etc. It rounds up the value that is actually stored, not the value you gave it to begin with.

http://msdn.microsoft.com/en-us/library/ms187912.aspx

If exact decimal math matters to you, use DECIMAL, not FLOAT or REAL.

like image 152
richardtallent Avatar answered Oct 04 '22 12:10

richardtallent