Groovy isInteger and toInteger
Groovy adds isInteger to check whether text can be converted to an Integer. toInteger performs the conversion.
A simple example
isInteger and toInteger
- Start with "12"
- Do this Read a base-ten integer
- Result 12
Syntax
text.isInteger() / text.toInteger()
Run this example in Groovy
Save the program as Lesson.groovy. Use Groovy 4 on the JVM.
groovy Lesson.groovy
Validate an integer before converting it
A shipment or sensor form accepts a number as text. Check both the allowed range and how much input was consumed so a partial number, invalid field or overflowing value cannot pass as a normal reading.
['0', '2147483648', '7kg'].each { field ->
println(field.isInteger() ? field.toInteger() : 'invalid')
}
0 invalid invalid
The check includes the Integer range. For a field wider than 32 bits, choose a wider conversion consistently for both validation and parsing.
Groovy documentation for isInteger and toInteger
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
Read an empty delivery count
A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?