0

XTRF Groovy Macro - How to compare numerical values with non-numeric value 'Hyphens'

burg 2 years ago updated by Bartosz Budzyński 2 years ago 2

How to check in XTRF Macros when value is a whole number or with decimal places and/or non-numeric values exists such as hyphens.

Example 1: Quote Value can be 0 
Example 2: Quote Value can be 0.00
Example 3: Quote Value can be -

+1

Dear Burg,

This is a plain java question that you have. I think the best thing you could do is to look into Google and get some examples there such as these https://www.baeldung.com/java-check-string-number

As example for your specific problem, this will give you a push in the right direction:

def num = '0'
def result = ''

if(isNumeric(num)) { result += '- number '; } // Example 1
if(isInteger(num)) { result += '- int ' } // Example 2
if(num.indexOf('-') > 0) { result += '- contains hyphens '  } // Example 3

result;

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    try {
        double d = Double.parseDouble(strNum);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}


public static boolean isInteger(String strNum) {
    if (strNum == null) {
        return false;
    }
    try {
        def i = Integer.parseInt(strNum);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

The important part is that the "-" is null in most places. It is just a visual placeholder for the front end to mark that there's "no value" in a given field. I'm not sure which field exactly you are talking about, but keep your eyes peeled :) 

That being said, here's the answer to your question: 

Checking if the given value is a specific type

That's very simple; you just need to use the instanceof operator.

def a = 3
def b = "s" 

a instanceof Integer
b instanceof Integer

// This will give you the true/false depending if that's the integer or not. 

if (!(a instanceof Integer) && a instanceof Number) { 
    "a is a floating point number!"
}


Comparing two numbers

The way to go is to use type casting as-is and handle the potential exception:

Integer a = 3
String b = "s" 

boolean compare(a,b) { 
    try {
        (a as BigDecimal) == (b as BigDecimal) 
    } catch(NumberFormatException nfe) { 
        println(nfe.message)
        return false
    }
}

Another way is to use the built-in Number class and/or the `instanceof` operator and type casting if you don't want to make the comparison if the type doesn't match: 

Integer a = 3
String b = "s" 

boolean compare_instanceof(a,b) { 
    if (a instanceof Number && b instanceof Number) { 
        return a == b
    }
    else { 
        return false
    }

}