0

I'm unmarshaling a remote call as a string and I would like to save it locally as a float32.

The string is 22.600 and when I parse that:

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

I get 22.600000381469727. Of course, that is not what I would like. How can I get a ParseFloat to exactly give me 22.600?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Tino
  • 3,340
  • 5
  • 44
  • 74
  • 5
    You can't. There are many resources about this on the web, for instance https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html . Do not use floating point for currency. – Burak Serdar Jan 17 '21 at 21:55
  • 4
    Floating point numbers often cannot represent finite decimal numbers. Use integers if you don't want those "artifacts", especially if you're dealing with money. – icza Jan 17 '21 at 21:55
  • use a format of %.3f But using actual floats for currency is a bad bad idea – Vorsprung Jan 17 '21 at 21:57
  • return float32(math.Round(f * 1000) / 1000) – Or Yaacov Jan 17 '21 at 23:27
  • 2
    Note that using floating point values for currency is usually _very dangerous_, due to the [imprecise nature](https://stackoverflow.com/q/21895756/13860) of floating point arethmetic! – Jonathan Hall Jan 18 '21 at 08:12

1 Answers1

1
func parseFloat(toParse string) float32 {
    toParse := "22.600000381469727"
    f, _ := strconv.ParseFloat(toParse, 32)
    s := fmt.Sprintf("%.3f", float32(f))
    return s
}
Omid Tavakoli
  • 156
  • 2
  • 5