Number Parsing in Groovy
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Groovy.
To run the program, save it as number-parsing.groovy
and use the groovy
command:
Groovy provides built-in methods for parsing numbers, which makes the process more straightforward compared to some other languages. The toFloat()
, toInteger()
, and toLong()
methods are used for parsing floating-point numbers, integers, and long integers respectively.
For hexadecimal numbers, we can use toInteger(16)
to specify the base.
Unlike some languages, Groovy doesn’t have unsigned types, so we use toLong()
for larger numbers that might exceed the range of a signed integer.
Groovy’s number parsing methods throw a NumberFormatException
when given invalid input, which we can catch and handle as shown in the last example.
Next, we’ll look at another common parsing task: URLs.