The following snippet
import "fmt"
func main() {
a := 8.9
b := 2.2
c := a + b
fmt.Printf("%g\n", c)
}
Returns 11.100000000000001
but i expect 11.1
What am i doing wrong ?
Thanks
The following snippet
import "fmt"
func main() {
a := 8.9
b := 2.2
c := a + b
fmt.Printf("%g\n", c)
}
Returns 11.100000000000001
but i expect 11.1
What am i doing wrong ?
Thanks
Hi @wdantuma ! In Go if you to want format correctly a
float
number with a specific number of decimals, you need to use %.Nf
where N is the number of digits you want.
In your case change:
with fmt.Printf("%.1f\n", c)
. The formatter %g
represents the float number with its maximum number of significant digits, and in your case you’re using two float64
so Go fills all the right 14 digits automatically
That’s just float…
If you need accurate results, just don’t use floats.
Some background info:
Thanks both, i should have known
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.