Ask a Question

How to get the number of decimal places in a given number

SOLVED
krkarthik_info
Frequent Contributor

How to get the number of decimal places in a given number

Hi,

 

I have a scenario where I need to get the number of decimal digits after the decimal point. Please refer below ex.

I want a function where I give this number as input and the function should return 4. As there are 4 decimal digits including trailing zeros.

 

var number = 123.1000;

 

Kindly someone help.

 

Thanks,

Karthik K R 

1 ACCEPTED SOLUTION

Accepted Solutions
PanB
Occasional Contributor

Re: How to get the number of decimal places in a given number

function count_fraction_length()

{

var number_to_string = "123.1000";

var length = number_to_string.length;

var position = number_to_string.indexOf(".")+1;

Log.Message(length-position);

}

 

You may need to convert duble to string.

 

 

 

View solution in original post

5 REPLIES 5
PanB
Occasional Contributor

Re: How to get the number of decimal places in a given number

function count_fraction_length()

{

var number_to_string = "123.1000";

var length = number_to_string.length;

var position = number_to_string.indexOf(".")+1;

Log.Message(length-position);

}

 

You may need to convert duble to string.

 

 

 

View solution in original post

baxatob
Community Hero

Re: How to get the number of decimal places in a given number

Using Python you can do it in very simple way:

 

 

def decimals(x):

    return len(str(x - int(x))[2:])

 

Algorithm is the following:

 

0. Let say: x = 10.1234

 

1. (x - int(x)) or (x % 1)    ->   remain only floating signs: 0.1234

 

2. (str(x - int(x))[2:])    ->    convert it into the string beginning after the floating point: "1234"

 

3. The length of the string is the number of decimals.

 

P.S. But in some cases you can have a rounding issues... So my solution is far from ideal... Smiley Frustrated

krkarthik_info
Frequent Contributor

Re: How to get the number of decimal places in a given number

Thanks for the solution.

krkarthik_info
Frequent Contributor

Re: How to get the number of decimal places in a given number

Thanks baxatob for the code.

baxatob
Community Hero

Re: How to get the number of decimal places in a given number

It looks like better to use aqConvert.FloatToStr() method and then parse the result using regular expression:

 

import re

def decimals(yourFloat):

    converted_num = aqConvert.FloatToStr(yourFloat)
    pattern = re.compile("\.[0-9]*")	
    res = re.search(pattern, converted_num)
    if res is not None:
        res = res.group(0)
	return len(res[1:])
    
cancel
Showing results for 
Search instead for 
Did you mean: