Question

Hello i am a beginner to groovy i am cofused how to check whether the given input is a number or not i tried the following

def a= ' 12.571245ERROR'
if(a.isNan()==0)
{
println("not a number")
}
else
{
println("number")
}

Kindly help me how to use isNan in groovy.I googled it lot but didnt find any result . Thanks in advance

Was it helpful?

Solution 3

You can try to cast it to number and catch an exception if its not a number

def a= ' 12.571245ERROR'

try {
    a as Double
    println "a is number"
}catch (e) {
    println "a is not a number"
}

Or

if(a instanceof Number)
    println "Number"
else
    println "NaN"

Although keep in mind, in the second way of checking it, it would fail even if a is a valid number but in a String like "123". 123 is Number but "123" is not.

OTHER TIPS

Groovy's String::isNumber() to the rescue:

def a = "a"

assert !a.isNumber()

def b = "10.90"

assert b.isNumber()
assert b.toDouble() == 10.90

To answer your question, I would not consider isNan(). It is mentioned on the web, but it does not appear in the String doc for the GDK.

Consider this:

def input = "12.37"
def isNumber = input.isDouble() 

println "isNumber : ${isNumber}"

Or use something that is more Java-esque:

def input = "12.37error"

def isNumber = false

try {
    double value = Double.parseDouble(input)
    isNumber = true
} catch (Exception ex) {
}

println "isNumber : ${isNumber}"

This will fail for the number format with commas (eg: 10,00,000)

def aNumber = "10,00,000" aNumber.isNumber() and aNumber.isDouble() give answer as false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top