Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does SQL Len Function Return 7 for this Query?

For this TSQL query:

SELECT CAST(116.33 / 8 AS FLOAT) AS [Float Value]
 , LEN(CAST(116.33 / 8 AS FLOAT)) AS [Length of Float Value]
 , LEN(CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR)) AS [Length Cast As Varchar]

Result:

Float Value  | Length of Float Value  |  Length Cast As Varchar
14.54125     | 7                      |  7

Why does LEN yield 7 instead of 8 when I cast as Varchar? Also, what implicit cast or conversion will yield 8 for LEN?

like image 769
C. Suttle Avatar asked Nov 27 '25 17:11

C. Suttle


1 Answers

Len function on Float in SQLServer gives wrong length is very related and @rbr94 's answer there explains it quite well:

LEN() works on [N]VARCHAR(), thus you're running into an implicit conversion from FLOAT to VARCHAR

It's easily proven by extending your query:

SELECT CAST(116.33 / 8 AS FLOAT) AS [Float Value]
 , LEN(CAST(116.33 / 8 AS FLOAT)) AS [Length of Float Value]
 , LEN(CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR)) AS [Length Cast As Varchar]
 , CAST(CAST(116.33 / 8 AS FLOAT) AS VARCHAR) AS [Cast As Varchar]

which gives

Float Value Length of Float Value   Length Cast As Varchar  Cast As Varchar
14.54125    7                       7                       14.5413
like image 156
fvu Avatar answered Nov 30 '25 08:11

fvu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!