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 nslt的可用模型,或者其他可以进行推理的现有模型
  • ¥15 arduino上连sim900a实现连接mqtt服务器
  • ¥15 vncviewer7.0安装后如何正确注册License许可证,激活使用
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并2
  • ¥66 关于人体营养与饮食规划的线性规划模型
  • ¥15 基于深度学习的快递面单识别系统
  • ¥15 Multisim仿真设计地铁到站提醒电路
  • ¥15 怎么用一个500W电源给5台60W的电脑供电
  • ¥15 请推荐一个轻量级规则引擎,配合流程引擎使用,规则引擎负责判断出符合规则的流程引擎模板id
  • ¥15 Excel表只有年月怎么计算年龄