解析字符串以浮动货币

时间:2021-01-17 21:52:46

标签: go

我将远程调用解组为字符串,我想将其保存在本地作为 float32。

字符串是 22.600,当我解析它时:

func parseFloat(toParse string) float32 {
    f, _ := strconv.ParseFloat(toParse, 32)
    return float32(f)
}

我得到 22.600000381469727。当然,这不是我想要的。我怎样才能让 ParseFloat 准确地给我 22.600?

1 个答案:

答案 0 :(得分:1)

func parseFloat(toParse string) float32 {
    toParse := "22.600000381469727"
    f, _ := strconv.ParseFloat(toParse, 32)
    s := fmt.Sprintf("%.3f", float32(f))
    return s
}