strconv.Atoi: parsing "X": invalid syntax

Go Programming Language

Severity: Minor

What it means

The message names the function and the text, such as strconv.Atoi: parsing "abc": invalid syntax. Go's own example: strconv.ParseFloat: parsing "Not a number": invalid syntax.
Go's docs: invalid syntax means the value doesn't have the right syntax for the target type.
A number too big for the type ends in value out of range instead.

Affected Models

  • Go programs at run time

How to Fix It

  1. Look at the text in quotes. A newline or space counts, so a line read from input fails as "42\n". Trim it first with strings.TrimSpace.

  2. Atoi reads whole numbers only. 3.5 or 1,000 fails. Use strconv.ParseFloat for decimals, and remove thousands separators first.

  3. parsing ""? The text was empty. Check for empty input before converting.

  4. Always check the error. errors.Is(err, strconv.ErrSyntax) or strconv.ErrRange tells you which problem it was.