← 中文资源

简体中文版本

用 strconv 格式化数字

strconv.FormatInt 按进制渲染整数、FormatFloat 定精度、AppendInt/AppendQuote 直接追加到字节切片避免中间分配,Quote 补引号并转义。

阅读英文原文

实现说明

用 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\""))
}