【问题标题】:Trouble using strconv.FormatFloat() in type switch在类型切换中使用 strconv.FormatFloat() 时遇到问题
【发布时间】:2014-07-15 01:06:36
【问题描述】:

我只是尝试使用类型开关来处理时间、float32s 和 float64s。它在时间和 float64s 上运行良好,但 strconv.FormatFloat(val, 'f', -1, 32) 一直告诉我我不能将 type float32 用作 type float64。我看不出这是怎么发生的,所以我一定是遗漏了一些东西或误解了我应该如何为float32s 打电话给FormatFloat()

func main() {
    fmt.Println(test(rand.Float32()))
    fmt.Println(test(rand.Float64()))
}

func test(val interface{}) string {
    switch val := val.(type) {
        case time.Time:
            return fmt.Sprintf("%s", val)
        case float64:
            return strconv.FormatFloat(val, 'f', -1, 64)
        case float32:
            return strconv.FormatFloat(val, 'f', -1, 32) //here's the error
        default:
            return "Type not supported!"
    }
}

错误:

不能在 strconv.FormatFloat 的参数中使用 val(float32 类型)作为 float64 类型

【问题讨论】:

    标签: go


    【解决方案1】:

    FormatFloat 的第一个参数必须是 float64,而您传递的是 float32。解决此问题的最简单方法是将 32 位浮点数转换为 64 位浮点数。

    case float32:
        return strconv.FormatFloat(float64(val), 'f', -1, 32)
    

    http://play.golang.org/p/jBPaQ-jMBT

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-16
      • 2012-02-04
      • 2012-05-08
      • 2015-08-25
      • 2020-12-18
      相关资源
      最近更新 更多