duanrang3357 2016-10-27 12:54 采纳率: 0%
浏览 22
已采纳

以最小宽度浮动到Golang中的字符串

I'm trying to get a float to print using fmt.Printf with a minimum width of 3

fmt.Printf("%3f", float64(0))

Should print 0.00, but it instead prints 0.000000 If I set the precision to 3, it truncates the value.

Basically, what I want is if the value is 0, it should print 0.00. If the value is 0.045, it should print 0.045, etc.

  • 写回答

3条回答 默认 最新

  • dongzi0602 2016-10-27 13:00
    关注

    This function should do what you want:

    func Float2String(i float64) string {
        // First see if we have 2 or fewer significant decimal places,
        // and if so, return the number with up to 2 trailing 0s.
        if i*100 == math.Floor(i*100) {
            return strconv.FormatFloat(i, 'f', 2, 64)
        }
        // Otherwise, just format normally, using the minimum number of
        // necessary digits.
        return strconv.FormatFloat(i, 'f', -1, 64)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 VS2022创建MVC framework提示:预安装的程序包具有对缺少的注册表值的引用
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义
  • ¥15 嵌入式--定时器使用
  • ¥20 51单片机学习中的问题
  • ¥30 Windows Server 2016利用兩張網卡處理兩個不同網絡
  • ¥15 Python中knn问题
  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库