golang printf float 没有前导零

标签 go printf

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/

相关文章:

linux - 如何停止 GCC 从 obj 文件中的字符串文字中剥离尾随换行符?

c - 如何将 printf 语句格式化为列名

go - 使用 testing.Benchmark 不会产生任何输出

go - 在 Golang 中像 PHP 一样打印网页源代码的一部分

map - 运行时错误 : assignment to entry in nil map

c - 使用 printf 在 C 中打印 float / double 时指定精度

c++ - 为什么 long long 值打印不正确?

java - 在 Windows 中从 golanguage 程序执行 jar

go - 为什么我的 D 代码没有达到预期的性能?

c - sprintf 的问题