Library contents

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

  1. Start with "12"
  2. Do this Read a base-ten integer
  3. Result 12
The characters 1 and 2 represent one ten and two ones. The resulting number can be used in arithmetic.

Syntax

Go 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.

First output line127
main.go
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)
	}
}
Output
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

Advertisements

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?

Given“18” + 2 on hand
Worked result20

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?

Given“0” + 2 on hand
Worked result2