Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Crystal.
To run the program, save it as number_parsing.cr and use the crystal command:
Crystal’s number parsing is somewhat different from Go’s:
Instead of a separate package, Crystal’s number parsing methods are part of the String class.
Crystal doesn’t require specifying bit precision for floating-point parsing; to_f returns a Float64 by default.
For integer parsing, Crystal’s to_i method assumes base 10 by default, but allows specifying a different base.
Crystal raises exceptions for parsing errors instead of returning error values.
There’s no direct equivalent to Go’s ParseUint, but Crystal provides to_u8, to_u16, to_u32, and to_u64 for parsing unsigned integers of different sizes.
Crystal’s approach to number parsing is more object-oriented and integrated into the language’s type system, reflecting its Ruby-inspired design.
Next, we’ll look at another common parsing task: URLs.