Allan F
Allan F

Reputation: 2288

How do I convert a float to varchar without loss of decimal places? SQL Server 2012

SQL Server 2012: converting a float to varchar is removing decimal places.

For example:

select convert(varchar, cast(834.7833 as float))

returns a varchar with 834.783.

How do I convert a float to varchar without loss of decimal places?

This is a similar question to this unanswered question:

How does convert(varchar, float) decide how many decimal places to keep?

Upvotes: 1

Views: 1455

Answers (2)

Kelly
Kelly

Reputation: 995

I had this problem as well. I have latitude and longitude float columns that contains numbers with around 4-6 decimal places. When I do cast(latitude as varchar(20)), it rounds the numbers with 6 decimal places to 4- so annoying! I found this solution (which I don't understand why I have to do this, but it works) where you cast it to a decimal first and then to a varchar.

select isnull(cast(cast(l.latitude as decimal(10,6)) as varchar(20)), 'Unknown') as latitude

One potential downside is that it adds trailing zeros, but that was fine with me.

Upvotes: 0

marc_s
marc_s

Reputation: 754348

Why do you need to do a CAST(... AS FLOAT) at all??

Try these snippets - they return the full number of decimal points:

SELECT
    CONVERT(VARCHAR(20), 834.7833)

SELECT
    CAST(834.7833 AS VARCHAR(20))

Both of these output this result:

834.7833

Upvotes: 1

Related Questions