gpt4 book ai didi

go - 在类型切换中使用 strconv.FormatFloat() 时遇到问题

转载 作者:IT王子 更新时间:2023-10-29 01:22:25 25 4
gpt4 key购买 nike

我只是想使用类型开关来处理时间、float32 和 float64。它适用于时间和 float64s,但 strconv.FormatFloat(val, 'f', -1, 32) 一直告诉我不能使用 type float32 作为类型 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!"
}
}

错误:

cannot use val (type float32) as type float64 in argument to strconv.FormatFloat

最佳答案

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

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

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

关于go - 在类型切换中使用 strconv.FormatFloat() 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748452/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com