Search code examples
sql-servert-sqlcountdigits

How would I count the number of digits to the right of the decimal in a floating point column?


I have table with Latitudes and Longitudes that are stored as floating points. How would I count the number of digits to the right of the decimal in the Latitude column? The data would look something like this:

    DECLARE @MyData TABLE (ID, Latitude float, Longitude float)
    INSERT @MyData

    SELECT 'A', 33.11, -55.2235 UNION ALL
    SELECT 'B', 33.6407760431,-87.0002760543 UNION ALL
    SELECT 'C', 42.2997,-70.9081; 

and I would want this in

    ID    |   LatitudeNumberOfDigits
     A    |    2
     B    |   10
     C    |    4

I was trying to convert it to text and split it up using a . as a delimiter but the CONVERT did not work as anticipated. It rounded to four significant digits

    SELECT ID, Latitude, Longitude, 
    CONVERT(varchar(max),[Latitude]) AS LatText 
    FROM @MyData

Gave me

     ID Latitude    Longitude        LatText
     A  33.11           -55.2235         33.11
     B  33.6407760431   -87.0002760543   33.6408
     C  42.2997         -70.9081         42.2997

Thanks !


Solution

  • Try this (it assumes that your floats will have at most 10 decimal places, otherwise adjust the values in STR).

    WITH MyData (ID, Latitude, Longitude)
    AS
    (
        SELECT 'A', CAST(33.11 AS FLOAT), CAST(-55.2235 AS FLOAT) UNION ALL
        SELECT 'B', 33.6407760431,-87.0002760543 UNION ALL
        SELECT 'C', 42.2997,-70.9081 
    )
    SELECT ID, Latitude, Longitude, 
        LEN(CAST(REVERSE(SUBSTRING(STR([Latitude], 13, 11), CHARINDEX('.', STR([Latitude], 13, 11)) + 1, 20)) AS INT)) AS LatText  
    FROM MyData
    

    As others have note, however, FLOATs are likely to give you some headaches. Consider this for instance:

    SELECT STR(33.11, 20,17) -- result: 33.1099999999999990