LEN function, know number of characters of a number

9

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

DECLARE @valor money = 10.6879

SELECT LEN(@Valor)

The impression I get 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 of a money number?

    
asked by anonymous 02.07.2018 / 20:54

3 answers

3

First create the function

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
    
02.07.2018 / 21:32
2

Convert using CONVERT to type DECIMAL ( reference here ):

DECLARE @valor money = 10.6879

SELECT LEN(CONVERT(decimal(6,4),@Valor)); //7
    
02.07.2018 / 21:14
2

The solution to your problem is simple:

DECLARE @Valor MONEY = 10.6879

SELECT LEN(CONVERT(FLOAT, @Valor)) -- 7

The difference for the @LeonardoBonetti example is the data type of the conversion ( FLOAT instead of DECIMAL(6, 4) ).

    
18.07.2018 / 23:31