How to check whether the input is a number or string by using isNan() in groovy
Asked Answered
C

4

5

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

Chiro answered 10/8, 2013 at 9:59 Comment(0)
S
4

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.

Sticky answered 10/8, 2013 at 10:26 Comment(1)
I'm not thrilled that this is the top answer, if the behaviour of the program is to handle the data whether it is a number type or otherwise, then an exception should not be used. exceptions, as their name suggests, catch unexpected/undesired behaviour.Rag
T
15

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
Tenant answered 10/8, 2013 at 13:4 Comment(0)
V
5

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}"
Valero answered 10/8, 2013 at 10:27 Comment(0)
S
4

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.

Sticky answered 10/8, 2013 at 10:26 Comment(1)
I'm not thrilled that this is the top answer, if the behaviour of the program is to handle the data whether it is a number type or otherwise, then an exception should not be used. exceptions, as their name suggests, catch unexpected/undesired behaviour.Rag
C
0

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.

Cytogenetics answered 15/10, 2018 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.