Strconv Parse And Format Roundtrip

Convert strings to numbers and back with strconv, surfacing parse errors as values instead of panics so bad input fails predictably.

GoData Integrity

Code

gosnippet
24 lines
package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Parse:错误作为值返回,不 panic
	n, err := strconv.Atoi("1234")
	fmt.Println(n, err)

	bad, err := strconv.Atoi("12a4")
	fmt.Println(bad, "err:", err)

	// ParseFloat 带位宽约束
	f, err := strconv.ParseFloat("3.14159", 64)
	fmt.Println(f, err)

	// Format:反向转换
	fmt.Println(strconv.Itoa(n))
	fmt.Println(strconv.FormatFloat(f, 'f', 2, 64))
	fmt.Println(strconv.Quote("hello\nworld"))
}

The structure at work

Strconv Parse And Format Roundtrip comes down to the function main.

The whole roundtrip lives in main. strconv.Atoi("1234") returns 1234 with a nil error, while strconv.Atoi("12a4") returns 0 plus the invalid-syntax error, so parse failures arrive as values instead of panics. strconv.ParseFloat("3.14159", 64) parses the float at 64-bit width, and the second half reverses the trip: strconv.Itoa(n) renders the integer back as 1234, strconv.FormatFloat(f, 'f', 2, 64) fixes two decimals as 3.14, and strconv.Quote wraps hello\nworld in quotes with the newline escaped.

Core lines

f, err := strconv.ParseFloat("3.14159", 64)

Interactive Tools for This Topic

FAQ

How do you run Strconv Parse And Format Roundtrip?
The file is self-contained: run it directly, no dependencies to install beforehand.