我有一行代码看起来像这样:
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/