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

在类型切换中使用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

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

报告相同问题?

悬赏问题

  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据