Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is casting from float to varchar being rounded in SQL Server?

The following SQL,

declare @a as float, @b as float

select @a=1.353954 , @b=1.353956
select 
CAST(@a as VARCHAR(40)) AS a_float_to_varchar ,
CAST(@b as VARCHAR(40)) AS b_float_to_varchar

results in

a_float_to_varchar                       b_float_to_varchar
---------------------------------------- ----------------------------------------
1.35395                                  1.35396

based on 'float' and 'real' (Transact-SQL).

Float has a precision of 15 digits, so I am not sure why the number is being rounded when converted to varchar.

like image 532
N30 Avatar asked Jun 28 '11 19:06

N30


1 Answers

Cast to decimal before casting to varchar:

declare @a as float, @b as float

select @a=1.353954 , @b=1.353956
select
CAST(CAST(@a AS DECIMAL(38,18)) as VARCHAR(40)) AS a_float_to_varchar ,
CAST(CAST(@b AS DECIMAL(38,18)) as VARCHAR(40)) AS b_float_to_varchar
like image 141
A-K Avatar answered Sep 23 '22 02:09

A-K