Casting float to varchar looses precision



  • SELECT CAST('8.202343' AS FLOAT), CAST(CAST('8.202343' AS FLOAT(53)) AS VARCHAR)
    

    produces:

    8.202343 8.20234

    but I would expect:

    8.202343 8.202343

    What is causing this issue and can SQL server be configured (ie. /wo changing the query) to prevent such loose FLOAT to VARCHAR conversion?

    demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=7ed89b9fa9be5826953f5df5dff4154a



  • as per micrsoft doc

    https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-2017#float-and-real-styles

    SELECT CAST('8.202343' as FLOAT), CONVERT(VARCHAR(20),CAST('8.202343' as FLOAT),1)
    

    As alternative you could do this:

    select CAST(PARSENAME(8.202343,2) as VARCHAR(20))+'.'+CAST(PARSENAME(8.202343,1) as varchar(20))
    

Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2