sql – LEN function, know the number of characters in a number

Question:

In the example below the query result instead of returning 7 is returned 5 .

DECLARE @valor money = 10.6879

SELECT LEN(@Valor)

The impression I have is that when the number is of type money , only 2 decimal places are considered.

What function would I use to return the exact number of characters from a number like money?

Answer:

First create the role

CREATE FUNCTION dbo.countDigits(@A float) RETURNS tinyint AS
BEGIN
declare @R tinyint
IF @A IS NULL 
   RETURN NULL
set @R = 0
while @A - str(@A, 18 + @R, @r) <> 0
begin
   SET @R = @R + 1
end
RETURN @R
END
GO

Then just use

SELECT LEN(cast(10.6879 as decimal)) + dbo.countDigits(10.6879) +  + 1 
//número antes da virgula + Número de casas depois da vírgular + 1 = 7
Scroll to Top