dsigh7478 2014-07-15 01:06
浏览 2794
已采纳

在类型切换中使用strconv.FormatFloat()遇到麻烦

I'm simply trying to use a type switch for handling times, float32s and float64s. It's working fine for times and float64s, but strconv.FormatFloat(val, 'f', -1, 32) keeps telling me that I can't use type float32 as type float64. I don't see how that could be happening, so I must be missing something or misunderstanding how I'm supposed to be calling FormatFloat() for float32s.

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!"
    }
}

Error:

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

  • 写回答

1条回答 默认 最新

  • doukai2839 2014-07-15 01:15
    关注

    The first argument to FormatFloat needs to be a float64, and you are passing a float32. The easiest way to fix this is to simply cast the 32bit float to a 64bit float.

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 Ubuntu20.04无法连接GitHub
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥30 C++行情软件的tick数据如何高效的合成K线