Forum Discussion

krkarthik_info's avatar
krkarthik_info
Frequent Contributor
8 years ago
Solved

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 

  • 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.

     

     

     

5 Replies

  • PanB's avatar
    PanB
    Occasional Contributor

    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.

     

     

     

  • baxatob's avatar
    baxatob
    Community Hero

    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... :smileyfrustrated:

      • baxatob's avatar
        baxatob
        Community Hero

        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:])