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.

// Groovy has built-in methods for parsing numbers, so we don't need to import any additional packages

def main() {
    // With parseFloat, we don't need to specify precision as Groovy handles it automatically
    def f = "1.234".toFloat()
    println f

    // For parsing integers, we can use toInteger() method
    def i = "123".toInteger()
    println i

    // Groovy can recognize hex-formatted numbers
    def d = "0x1c8".toInteger(16)
    println d

    // For parsing unsigned integers, we can use toLong() as Groovy doesn't have unsigned types
    def u = "789".toLong()
    println u

    // Groovy's toInteger() is equivalent to Atoi for basic base-10 int parsing
    def k = "135".toInteger()
    println k

    // Parse functions will throw a NumberFormatException on bad input
    try {
        "wat".toInteger()
    } catch (NumberFormatException e) {
        println e.message
    }
}

main()

To run the program, save it as number-parsing.groovy and use the groovy command:

$ groovy number-parsing.groovy
1.234
123
456
789
135
For input string: "wat"

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.