Number Parsing in Squirrel

Here’s the translated code and explanation in Markdown format suitable for Hugo:

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Java.

The Integer, Long, Float, and Double classes provide number parsing functionality in Java.

public class NumberParsing {
    public static void main(String[] args) {
        // With parseFloat, we don't need to specify precision as Java handles it internally
        float f = Float.parseFloat("1.234");
        System.out.println(f);

        // For parseInt, we don't need to specify the base or bit size
        int i = Integer.parseInt("123");
        System.out.println(i);

        // parseInt will recognize hex-formatted numbers when we specify the radix
        int d = Integer.parseInt("1c8", 16);
        System.out.println(d);

        // parseLong is available for parsing to long
        long u = Long.parseLong("789");
        System.out.println(u);

        // Integer.parseInt is equivalent to Atoi in Go
        int k = Integer.parseInt("135");
        System.out.println(k);

        // Parse methods throw NumberFormatException on bad input
        try {
            Integer.parseInt("wat");
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
        }
    }
}

To run the program:

$ javac NumberParsing.java
$ java NumberParsing
1.234
123
456
789
135
For input string: "wat"

In Java, we use the wrapper classes (Integer, Long, Float, Double) to parse strings into their respective number types. These classes provide static methods like parseInt(), parseLong(), parseFloat(), and parseDouble().

Unlike in some other languages, Java doesn’t require specifying the bit size for parsing, as the types have fixed sizes (e.g., int is always 32 bits, long is always 64 bits).

For parsing hexadecimal numbers, we can use the parseInt() or parseLong() method with a radix of 16.

Java doesn’t have a direct equivalent to Go’s Atoi(), but Integer.parseInt() serves the same purpose for parsing base-10 integers.

When parsing fails due to invalid input, Java throws a NumberFormatException instead of returning an error value.

Next, we’ll look at another common parsing task: URLs.