Number Parsing
strconv.Atoi and ParseInt for integers, ParseFloat for floats, FormatInt and Itoa for the reverse, and error handling on invalid input.
The strconv package converts between text and numbers. Atoi reads decimal digits as an int. ParseInt lets you choose the number base, such as decimal or hexadecimal, and the size of the result. ParseFloat reads a decimal number. FormatInt and Itoa turn integers back into text.
Every parse returns an error. Check it because zero is also a valid parsed number.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
if err != nil {
panic(err)
}
fmt.Println(n)
_, err = strconv.ParseInt("256", 10, 8)
fmt.Println(err)
}In production
Check and handle a parse error before using the number. ParseInt's bit size sets how large or small the result may be, so the text can contain a number that is too large for the requested type. Use strconv for these conversions instead of reading formatted text with a scanner.