Go strconv.ParseInt
strconv.ParseInt converts a complete string to a signed integer in the requested base and checks the requested bit width.
A simple example
strconv.ParseInt
- Start with "12"
- Do this Read a base-ten integer
- Result 12
Syntax
n, err := strconv.ParseInt(text, 10, 8)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Validate a signed 8-bit reading
A shipment or sensor form accepts a number as text. Check both the allowed range and how much input was consumed so a partial number, invalid field or overflowing value cannot pass as a normal reading.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, field := range []string{"127", "128", "12kg"} {
n, err := strconv.ParseInt(field, 10, 8)
if err != nil {
fmt.Println("invalid")
continue
}
fmt.Println(n)
}
}
127 invalid invalid
The Go result type is int64 even when bitSize is 8. Reject an error before using n because an out-of-range input can also return a saturated value.
Go documentation for strconv.ParseInt
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
Read an empty delivery count
A class receives a stock record whose quantity field is the character zero. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?