golang printf float no leading zero

huangapple go评论74阅读模式
英文:

golang printf float no leading zero

问题

http://play.golang.org/p/3mjFDTTOXG

使用printf函数打印整数是可以的,但是对于浮点数,我得不到前导零。

fmt.Printf("%03.6f\n", 1.234)
// 输出:1.234000

为什么会这样?如何显示前导零?

Go语言版本为v1.4.1

编辑

我找到解决方法了:

fmt.Printf("%010.6f\n", 1.234)

现在可以显示前导零了。

编辑

来自https://golang.org/pkg/fmt/:

宽度和精度以Unicode代码点为单位进行测量。这与C语言的printf不同,C语言的单位始终以字节为单位。宽度和精度中的任意一个或两个标志可以被字符'*'替换,这样它们的值将从下一个操作数中获取,该操作数必须是int类型。

英文:

http://play.golang.org/p/3mjFDTTOXG

printf int is ok, but with float, I got no leading zero.

fmt.Printf("%03.6f\n", 1.234)
>1.234000

Why this happen ?How to make the leading zero display ?

golang v1.4.1

EDIT

I figured it out

fmt.Printf("%010.6f\n", 1.234)

this is ok now.

EDIT

from 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.

答案1

得分: 4

原因是您将要打印的字符串的精度设置为6,而宽度只设置为3。根据fmt包的说明:

宽度是在动词之后紧跟的一个可选十进制数来指定的。如果没有指定,宽度将根据值的表示所需的宽度确定。精度是在(可选的)宽度之后由一个点和一个十进制数指定的。如果没有点,将使用默认精度。

...

0表示用前导零而不是空格填充;对于数字,这将在符号之后填充。

因此,您得到了1.234000。要获得前导0,您需要将字符串的宽度增加到8(1 + . + 234000的长度)。因此,使用%09.6f,您将得到01.234000

英文:

The reason is that you set 6 as the precision of the string that will be printed and only 3 as the width. From the 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

Thus you get 1.234000. To get leading 0s you need to increase the width of the string past 8 (length of 1 + . + 234000). So with %09.6f you'll get 01.234000

huangapple
  • 本文由 发表于 2015年4月22日 22:01:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/29799968.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定