Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the count of digits after the decimal point in a float column in ms sql?

Tags:

sql-server

I have to count the digits after the decimal point in a database hosted by a MS Sql Server (2005 or 2008 does not matter), in order to correct some errors made by users. I have the same problem on an Oracle database, but there things are less complicated. Bottom line is on Oracle the select is:

select length( substr(to_char(MY_FIELD), instr(to_char(MY_FILED),'.',1,1)+1, length(to_char(MY_FILED)))) as digits_length
from MY_TABLE

where the filed My_filed is float(38).

On Ms Sql server I try to use:

select LEN(SUBSTRING(CAST(MY_FIELD AS VARCHAR), CHARINDEX('.',CAST(MY_FILED AS VARCHAR),1)+1, LEN(CAST(MY_FIELD AS VARCHAR)))) as digits_length
from MY_TABLE

The problem is that on MS Sql Server, when i cast MY_FIELD as varchar the float number is truncated by only 2 decimals and the count of the digits is wrong. Can someone give me any hints?

Best regards.

like image 448
BogdanM Avatar asked Dec 19 '12 13:12

BogdanM


2 Answers

SELECT 
LEN(CAST(REVERSE(SUBSTRING(STR(MY_FIELD, 13, 11), CHARINDEX('.', STR(MY_FIELD, 13, 11)) + 1, 20)) AS decimal)) 
from TABLE
like image 145
Elle Absolute Avatar answered Nov 15 '22 06:11

Elle Absolute


I have received from my friend a very simple solution which is just great. So I will post the workaround in order to help others in the same position as me.

First, make 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

Second:

select MY_FIELD,
dbo.countDigits(MY_FIELD) 
from MY_TABLE

Using the function will get you the exact number of digits after the decimal point.

like image 23
BogdanM Avatar answered Nov 15 '22 04:11

BogdanM