【问题标题】:Float to string in Golang with a minimum width在 Golang 中以最小宽度浮动到字符串
【发布时间】:2023-04-07 14:47:01
【问题描述】:

我正在尝试使用 fmt.Printf 打印一个最小宽度为 3 的浮点数

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

应该打印0.00,但它会打印0.000000 如果我将精度设置为 3,它会截断值。

基本上,我想要的是如果值为 0,它应该打印0.00。如果值为0.045,则应打印0.045等。

【问题讨论】:

    标签: go


    【解决方案1】:

    这个函数应该做你想做的:

    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 位,但它具有打印整个值的精度。
    • 是的,就是这样
    【解决方案2】:

    使用strconv.FormatFloat,例如,像这样:

    https://play.golang.org/p/wNe3b6d7p0

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        fmt.Println(strconv.FormatFloat(0, 'f', 2, 64))
        fmt.Println(strconv.FormatFloat(0.0000003, 'f', -1, 64))
    }
    

    0.00
    0.0000003

    有关其他格式选项和模式,请参阅链接文档。

    【讨论】:

      【解决方案3】:

      你少了一个点

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

      将打印出:0.000

      示例:https://play.golang.org/p/n6Goz3ULcm

      【讨论】:

      • 这会截断值。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多