package main
import (
"fmt"
)
func main() {
fmt.Println(float64(1/2))
}
Why it prints: 0
Playground link: https://play.golang.org/p/KGgao6n8lTA
Is it because fmt.Println
precision is low?
package main
import (
"fmt"
)
func main() {
fmt.Println(float64(1/2))
}
Why it prints: 0
Playground link: https://play.golang.org/p/KGgao6n8lTA
Is it because fmt.Println
precision is low?
The order of operations here is: 1/2 = 0
(integer division truncates decimal places) followed by float64(0) = 0
, then fmt.Println(0)
.
So in short: the integer division is truncated to 0. Everything else works fine.
As @Amadan commented, you can force a floating point division by casting one of the integers, i.e. float64(1) / 2 = 0.5
.