Number Parsing in Nim

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

import strutils

# With parseFloat, we don't need to specify precision as Nim handles it automatically
let f = parseFloat("1.234")
echo f

# For parseInt, we don't need to specify base or bit size
let i = parseInt("123")
echo i

# parseInt will recognize hex-formatted numbers with the 0x prefix
let d = parseInt("0x1c8")
echo d

# For parsing unsigned integers, we use parseUInt
let u = parseUInt("789")
echo u

# Nim doesn't have a direct equivalent to Atoi, but parseInt works for basic base-10 int parsing
let k = parseInt("135")
echo k

# Parse functions raise ValueError on bad input
try:
  discard parseInt("wat")
except ValueError as e:
  echo e.msg

The strutils module in Nim provides number parsing functionality, similar to the strconv package in other languages.

With parseFloat, Nim automatically handles the precision, so we don’t need to specify it.

For parseInt, Nim infers the base from the string (recognizing prefixes like 0x for hexadecimal) and automatically handles different integer sizes, so we don’t need to specify these parameters.

Nim uses parseUInt for parsing unsigned integers.

Nim doesn’t have a direct equivalent to Atoi, but parseInt serves the same purpose for basic base-10 integer parsing.

Parse functions in Nim raise a ValueError on bad input, which we can catch using a try-except block.

When you run this program, you’ll see output similar to:

1.234
123
456
789
135
invalid integer: wat

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