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.
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:
Next, we’ll look at another common parsing task: URLs.