Go语言整数格式化输出:轻松添加千分位分隔符
本文介绍如何使用Go语言编写函数,将整数格式化为带有千分位分隔符的字符串。例如,输入1234567,输出为1,234,567。我们将逐步讲解实现方法。
目标:编写一个名为trans
的Go函数,接收整数n
作为输入,返回格式化后的字符串,每三位数字以逗号分隔。示例:
Go语言实现:
以下Go代码实现了上述功能,其逻辑是从右到左遍历数字字符串,每三位添加逗号:
package main import ( "fmt" "strconv" ) func trans(n int) string { s := strconv.Itoa(n) ans := "" count := 0 for i := len(s) - 1; i >= 0; i-- { ans = string(s[i]) + ans count++ if count%3 == 0 && i != 0 { ans = "," + ans } } return ans } func main() { fmt.Println(trans(123)) // 123 fmt.Println(trans(1234)) // 1,234 fmt.Println(trans(123456)) // 123,456 fmt.Println(trans(1234567)) // 1,234,567 fmt.Println(trans(123456789)) // 123,456,789 }
这段代码简洁高效地实现了千分位分隔符的添加。 它先将整数转换为字符串,然后逆序遍历,每隔三位插入逗号。 count
变量用于跟踪数字的位数,确保逗号添加位置正确。