Reputation: 3663
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.
Upvotes: 13
Views: 35504
Reputation: 1009
You can specify style to include more digits.
declare @gg float
set @gg = 124.323125453
SELECT @gg,Convert(varchar, @gg,128)
For newer versions of SQL Server, use SELECT @gg,Convert(varchar, @gg,3)
returns
124.323125453 124.323125453
Reference: CAST and CONVERT (Transact-SQL)
Or with STR():
declare @gg float
set @gg = 124.323124354234524
SELECT @gg,str(@gg,16,15)
It should give you all the possible digits. 16 is the total possible length (includes period) while 15 places after the decimal is possible (actually 0.2323... the 0 count toward length, so the length needs to be 17 if all numbers are less that 1). STR(), however, pads the results with leading spaces and trailing 0.
Upvotes: 6
Reputation: 17080
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
Upvotes: 6