groovysignificant-digits

I need to create a function in Groovy that has a single integer as a parameter and returns the number of significant figures it contains


Long story short, I'm working in a system that only works with groovy in its expression editor, and I need to create a function that returns the number of significant figures an integer has. I've found the following function in stack overflow for Java, however it doesnt seem like groovy (or the system itself) likes the regex:

String myfloat = "0.0120";

String [] sig_figs = myfloat.split("(^0+(\\.?)0*|(~\\.)0+$|\\.)");

int sum = 0;

for (String fig : sig_figs)
{
    sum += fig.length();
}

return sum;

I've since tried to convert it into a more Groovy-esque syntax to be compatible, and have produced the following:

def sum = 0;

def myint = toString(mynum);

def String[] sig_figs = myint.split(/[^0+(\\.?)0*|(~\\.)0+$|\\.]/);

for (int i = 0; i <= sig_figs.size();i++)
{
    sum += sig_figs[i].length();
}
return(sum); 

Note that 'mynum' is the parameter of the method

It should also be noted that this system has very little visibility in regards to what groovy functions are available in the system, so the solution likely needs to be as basic as possible

Any help would be greatly appreciated. Thanks!


Solution

  • I think this is the regex you need:

    def num = '0.0120'
    def splitted = num.split(/(^0+(\.?)0*|(~\.)0+$|\.)/)
    def sf = splitted*.length().sum()