Format Numbers With Strconv
Render integers in any base, floats with fixed precision, and quoted strings with strconv.Format* and Append* helpers for allocation-free building.
Code
package main
import (
"fmt"
"strconv"
)
func main() {
// FormatInt formats whole numbers in any base from 2 to 36
n := int64(255)
fmt.Println(strconv.FormatInt(n, 2), strconv.FormatInt(n, 16))
// 浮点:'f' 表示无指数记法,精度 2 直接截位四舍五入
f := 3.14159
fmt.Println(strconv.FormatFloat(f, 'f', 2, 64))
// Append* 系列:追加到既有字节切片,避免中间字符串分配
buf := strconv.AppendInt([]byte("id="), 42, 10)
buf = strconv.AppendQuote(buf, "alice")
fmt.Println(string(buf))
// Quote 给字符串加引号并转义内部引号
fmt.Println(strconv.Quote("he said \"hi\""))
}What the code does
Format Numbers With Strconv comes down to the function main.
main exercises both halves of the strconv formatting surface. strconv.FormatInt(n, 2) supports bases 2 through 36 — the call renders 255 as 11111111 in base 2 and ff in base 16. strconv.FormatFloat(f, 'f', 2, 64) prints 3.14, where the f verb keeps non-exponential notation and the precision digit rounds. The Append path starts from the literal bytes id=, appends 42 with strconv.AppendInt, then a quoted alice with strconv.AppendQuote, producing id="alice" without an intermediate string allocation. The closing strconv.Quote call wraps he said "hi" in quotes with the inner quotes escaped.
Key statements
buf := strconv.AppendInt([]byte("id="), 42, 10)
Interactive Tools for This Topic
FAQ
- How do you run Format Numbers With Strconv?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.