http://play.golang.org/p/3mjFDTTOXG
printf int 没问题,但是对于 float,我没有前导零。
fmt.Printf("%03.6f\n", 1.234)
>1.234000
为什么会这样?如何显示前导零?
golang v1.4.1
编辑
我想通了
fmt.Printf("%010.6f\n", 1.234)
现在可以了。
编辑
来自 https://golang.org/pkg/fmt/
Width and precision are measured in units of Unicode code points, that is, runes. (This differs from C's printf where the units are always measured in bytes.) Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand, which must be of type int.
最佳答案
原因是您将要打印的字符串的精度设置为 6,而宽度仅设置为 3。来自fmt package.
Width is specified by an optional decimal number immediately following 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.
...
0 pad with leading zeros rather than spaces;
for numbers, this moves the padding after the sign
因此你得到 1.234000。要获得前导 0,您需要将字符串的宽度增加到 8(长度为 1 + . + 234000)。所以使用 %09.6f
你会得到 01.234000
关于golang printf float 没有前导零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29799968/