Title here
Summary here
Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Crystal.
# The built-in String class provides number parsing methods.
# With `to_f`, this parses the string to a Float64.
f = "1.234".to_f
puts f
# For integer parsing, we can use `to_i`.
# By default, it assumes base 10.
i = "123".to_i
puts i
# We can specify a different base for integer parsing.
d = "0x1c8".to_i(base: 16)
puts d
# There's also a method for parsing unsigned integers.
u = "789".to_u64
puts u
# Crystal doesn't have a direct equivalent to Go's Atoi,
# but we can use `to_i` for basic base-10 int parsing.
k = "135".to_i
puts k
# Parse methods raise an exception on bad input.
begin
"wat".to_i
rescue ex
puts ex
end
To run the program, save it as number_parsing.cr
and use the crystal
command:
$ crystal number_parsing.cr
1.234
123
456
789
135
Invalid Int32: wat
Crystal’s number parsing is somewhat different from Go’s:
String
class.to_f
returns a Float64
by default.to_i
method assumes base 10 by default, but allows specifying a different base.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.