Number Parsing in Julia

Here’s the translated code and explanation in Julia, formatted in Markdown suitable for Hugo:

Our first example demonstrates how to parse numbers from strings in Julia. This is a common task in many programs.

# The built-in parse function provides number parsing in Julia

# With parse, we specify the type we want to parse to
f = parse(Float64, "1.234")
println(f)

# For integers, we can use parse with Int64
i = parse(Int64, "123")
println(i)

# parse will recognize hex-formatted numbers when we specify base 16
d = parse(Int64, "0x1c8", base=16)
println(d)

# We can also parse unsigned integers
u = parse(UInt64, "789")
println(u)

# tryparse is a convenient function that returns nothing on invalid input
k = tryparse(Int64, "135")
println(k)

# tryparse returns nothing for invalid input
e = tryparse(Int64, "wat")
println(e)

To run the program, save it as number_parsing.jl and use the Julia REPL or run it from the command line:

$ julia number_parsing.jl
1.234
123
456
789
135
nothing

Let’s break down the key points:

  1. Julia’s parse function is used to convert strings to numbers. It takes two arguments: the type to parse to and the string to parse.

  2. For floating-point numbers, we use parse(Float64, ...).

  3. For integers, we use parse(Int64, ...). The base can be specified as an optional argument.

  4. Hexadecimal numbers are parsed by specifying base=16.

  5. Unsigned integers can be parsed using parse(UInt64, ...).

  6. tryparse is a safe alternative that returns nothing instead of throwing an error for invalid input.

  7. Julia’s type system allows for easy specification of the desired numeric type (Float64, Int64, UInt64, etc.).

This example demonstrates Julia’s straightforward approach to number parsing, which is both flexible and type-safe. The parse and tryparse functions provide a clean and consistent interface for converting strings to various numeric types.

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