Error converting float to varchar in SQL

Juan Pablo Echevarria 11 Reputation points
2022-03-30T22:47:20.767+00:00

I've found an error while trying to convert a float to varchar, using "style 3" (view style doc in here: cast-and-convert-transact-sql )

CODE

select convert(varchar(max),convert(float,-1),3)  

ERROR:

Msg 232, Level 16, State 2, Line 81  
Arithmetic overflow error for type varchar, value = -0.500000.  

Has anyone else seen this error? I found a solution so I post it here .

CAUSE:
The issue comes from using varchar(max).

SOLUTION:
Instead of using varchar(max) use varchar(n) and the error goes away.

WORKARROUND:
You could also use the style = 2, but you wouldn't get the maximum precision in the convertion (according to the docs).

select convert(varchar(max),convert(float,-1),2)  
Developer technologies Transact-SQL
0 comments No comments
{count} vote

3 answers

Sort by: Most helpful
  1. Naomi Nosonovsky 8,431 Reputation points
    2022-03-31T01:42:47.447+00:00

    Interesting, looks like a bug to me.

    0 comments No comments

  2. Olaf Helper 47,436 Reputation points
    2022-03-31T05:51:19.753+00:00

    Works for me/my SQL Server. Which version are you using? =>

    SELECT @@VERSION  
    

    188585-image.png


  3. Bert Zhou-msft 3,436 Reputation points
    2022-03-31T07:47:52.103+00:00

    Hi,@Juan Pablo Echevarria

    Welcome to Microsoft T-SQL Q&A Forum!

    Let me guess if your version is based on 2019linux, it seems that I have encountered this problem before, my approach is to receive the converted value through a variable, you can try it.

    DECLARE @dt DECIMAL(38);  
    SET @dt = convert(float,-1)  
    SELECT CAST(@dt AS VARCHAR(max))  
    

    ![188682-image.png]1

    Best regards,
    Bert Zhou


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.