duanmu6752 2015-04-22 14:01 采纳率: 0%
浏览 105
已采纳

golang printf float没有前导零

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

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

fmt.Printf("%03.6f
", 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
", 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条回答 默认 最新

  • dpkk8687 2015-04-22 14:14
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图