Golang 字符串格式给出了意想不到的间距

标签 go

我有一行代码看起来像这样:

fmt.Printf("Total Calories: %2.f (%2.f%%)\n", item.calorie.TotalCalories, item.calorie.TotalCalories/dailyCalorie*100)

它应该输出:

Total Calories: 150 (5%)

但是我得到的是括号开头和数字 5 之间的间距,如下所示:

Total Calories: 150 ( 5%)

我不明白我哪里做错了。

最佳答案

%2.f 给出的默认宽度为 2。您可以只尝试 %f

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:

%f     default width, default precision
%9f    width 9, default precision
%.2f   default width, precision 2
%9.2f  width 9, precision 2
%9.f   width 9, precision 0

您可以阅读文档 here.

关于Golang 字符串格式给出了意想不到的间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50107493/

相关文章:

go - 无法安装fabric-sdk-go及其依赖项

typescript - 使用 golang 生成头文件/声明文件 - 都在一个文件中?

Golang requestId 日志记录

go - HTTP : panic serving 127. 0.0.1:48286: EOF

go - 如何使用 golang 上下文功能而不是 golang http 客户端发出 http 请求?

Go 语言字符串常量

go - 是否有一种有效的方式来回收过剩容量的 slice ?

go - 了解结构嵌入

go - 多个goroutine的调度

programming-languages - 'systems language' 是什么意思?