Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to decimal in SQL Server 2008

I have a view which needs to return type decimal for columns stored as float.

I can cast each column to decimal as follows:

, CAST(Field1 as decimal) Field1

The problem with this approach, is that decimal defaults to 18,0, which automatically rounds the float columns to 0. I would like to keep a precision of up to 12 decimal places.

However, if I do this:

, CAST(Field1 as decimal(12,12)) Field1

I get a runtime error:

"Arithmetic overflow error converting float to data type numeric"

the float column is defined as length: 8 Precision: 53 in the table. I can not modify anything about the table.

What's the proper way to cast it as decimal w/out losing decimal precision?

like image 893
Sonic Soul Avatar asked Nov 15 '10 16:11

Sonic Soul


People also ask

How do you convert float to decimal?

The rules for converting a floating point number into decimal are simply to reverse of the decimal to floating point conversion: If the original number is in hex, convert it to binary. Separate into the sign, exponent, and mantissa fields. Extract the mantissa from the mantissa field, and restore the leading one.

How do I convert a number to a decimal in SQL?

Use the CAST() function to convert an integer to a DECIMAL data type. This function takes an expression or a column name as the argument, followed by the keyword AS and the new data type. In our example, we converted an integer (12) to a decimal value (12.00).

How do you set decimals in SQL Server?

The Basic syntax of Decimal data type in SQL Server It is denoted as below: decimal [(p [,s])]


1 Answers

12, 12 means no digits before the decimal separator: 12 digits in total, 12 of them being after the period.

Use a more appropriate range, say:

DECLARE @var FLOAT = 100
SELECT  CAST(@var as decimal(20,12))

which gives you 8 digits before the separator, or adjust it as needed.

like image 197
Quassnoi Avatar answered Sep 19 '22 14:09

Quassnoi