实现说明
用 strconv 格式化数字以函数 main为骨架。
常见问题
「用 strconv 格式化数字」这个示例怎么运行?
直接执行即可——程序只依赖运行时自身。
核心语句
buf := strconv.AppendInt([]byte("id="), 42, 10)
代码示例
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\""))
}