Floating points in Golang are numbers that contain decimal parts in it. For example 1.43, 23.54, etc
- Types of Floating Points in Golang
- Write a program to add two float32 numbers in Golang
- Write a program to add two float64 numbers in Golang
- Write a program to add one Float32 and one Float64 number in Golang
- References
Types of Floating Points in Golang
Go has two floating point data types
- Float32
- Float64
Float64 has more precision than Float32, so if you want to denote the decimal values accurately, you should use Float64. Also, Float64 will take more space than the Float32 numbers.
- Float32 is referred to as single precision
- Float64 is referred to as double precision
Write a program to add two float32 numbers in Golang
package main
import "fmt"
func main() {
var firstNumber float32 = 1.567
var secondNumber float32 = 3.89
fmt.Println(firstNumber + secondNumber)
}
Bash
➜ go run main.go
5.4570003
we took two float32 numbers and then performed addition over them.
Write a program to add two float64 numbers in Golang
package main
import "fmt"
func main() {
var firstNumber float64 = 1.567
var secondNumber float64 = 3.89
fmt.Println(firstNumber + secondNumber)
}
Bash
➜ go run main.go
5.457
Write a program to add one Float32 and one Float64 number in Golang
package main
import "fmt"
func main() {
var firstNumber float32 = 1.567
var secondNumber float64 = 3.89
fmt.Println(firstNumber + secondNumber)
}
Bash
➜ go run main.go
# command-line-arguments
./main.go:9:14: invalid operation: firstNumber + secondNumber (mismatched types float32 and float64)
This will throw an error as mismatched types of float32 and float64 because they do not have the same precision. You can fix this program by casting the float32 number to float64