Problem converting float32 to string

I have problem with float32 to string conversion.
My test code:

package main
import (

func main() {
    var t float32
    t = 5.9902389
	numeroString := strconv.FormatFloat(float64(t), 'f', -1, 32)
	fmt.Println("Number float32:", t)
	fmt.Println("Number string:", numeroString)

Number float32: 5.9902387
Number string: 5.9902387

For me, the response is “5.9902389” How to get exactly string representation for a float32,
when i don’t know the number precision?

I don’t have a fixed number of decimal places.
thanks in advance

Can’t reproduce on the playground…

The program here produces (your) exptected result.

Though given this is a float, whatever you get is garbage anyway. The exact number is not representable as float32. The exact stored number can be checked using IEEE-754 Floating Point Converter.

If you expect exact results use an exact number type.

Expanding on NobbZ’s answer: 5.9902387 is the exact minimum number of digits for a decimal representation of the 32-bit floating point number closest to 5.9902389. FWIW, I see 5.9902387 printed from the playground link. I read NobbZ’s answer to mean that he got 5.9902389.

Unfortunately for this case, the FloatConverter he linked to uses float64 and I don’t see an option for float32. Almost everyone always uses float64 all the time now anyway.

If you need eight digits of accuracy, just use float64 instead of float32, but maybe your example is a simplification of your real problem. More bits means more accuracy. If you need even more accuracy, you’ll pay a heavy performance penalty. It may be worth it depending on your use case.

I got what you have on your screenshot, though I understood OP that they expected same numbers to be printed, but actually got different…

If you need accuracy, you don’t use floats.

1 Like

"If you need accuracy, you don’t use floats. " How is the better aprouch for accurancy?

fixed points, decimals, integers.

Decimal is suported from this packge GitHub - shopspring/decimal: Arbitrary-precision fixed-point decimal numbers in go
Go has a internal type for that?

Physical measurements have a specific number of significant figures. You don’t need more digits than there are significant figures. Numerical analysis is built on calculating to reduce errors from floating point arithmetic to tolerable levels. Scientific computing works well in floating point numbers. Financial applications or other applications may be different. If you need performance, then don’t use arbitrary precision.

Significancy is usually specified in decimal places, not binary. If you need accuracy you don’t use floats.

1 Like

Thanks for the help

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.