C. Suttle
C. Suttle

Reputation: 190

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?

Upvotes: 3

Views: 161

Answers (3)

fvu
fvu

Reputation: 32953

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

Upvotes: 2

R.Eduard
R.Eduard

Reputation: 26

Please correct me if I am wrong but, the standard precision of float is 7 therefore here might be your problem.

You first cast the result to float which results in 7 digits.

plese view this microsoft post

Upvotes: 0

Related Questions