In this tutorial, we will learn about the float64 data type in Go. We will cover the basics of defining and using float64 values, including how to perform arithmetic operations and format floating-point numbers.
The float64
data type in Go is used to represent 64-bit floating-point numbers. It provides higher precision compared to float32
and is commonly used for scientific calculations and other applications requiring high precision.
Float64 variables in Go can be defined using the var
keyword or by type inference.
var f1 float64 = 3.14159265359
f2 := 2.71828182846
Arithmetic operations such as addition, subtraction, multiplication, and division can be performed on float64 values.
sum := f1 + f2
difference := f1 - f2
product := f1 * f2
quotient := f1 / f2
Float64 values can be formatted for output using the fmt
package.
fmt.Printf("%.10f", f1)
We can define and use float64 variables in Go to represent 64-bit floating-point values.
For example,
f1
and assign it a value.f2
using type inference and assign it a value.package main
import "fmt"
func main() {
var f1 float64 = 3.14159265359
f2 := 2.71828182846
fmt.Println(f1)
fmt.Println(f2)
}
3.14159265359 2.71828182846
We can perform arithmetic operations on float64 values in Go.
For example,
f1
and f2
.package main
import "fmt"
func main() {
f1 := 3.14159265359
f2 := 2.71828182846
sum := f1 + f2
difference := f1 - f2
product := f1 * f2
quotient := f1 / f2
fmt.Println("Sum:", sum)
fmt.Println("Difference:", difference)
fmt.Println("Product:", product)
fmt.Println("Quotient:", quotient)
}
Sum: 5.85987448205 Difference: 0.42331082513 Product: 8.53973422267 Quotient: 1.15572734979
We can format float64 values for output in Go using the fmt package.
For example,
f
and assign it a value.Printf
function from the fmt
package to format the float64 value with ten decimal places.package main
import "fmt"
func main() {
f := 3.14159265359
fmt.Printf("%.10f\n", f)
}
3.1415926536
We can compare float64 values in Go using relational operators.
For example,
f1
and f2
with different values.package main
import "fmt"
func main() {
f1 := 3.14159265359
f2 := 2.71828182846
fmt.Println(f1 > f2) // true
fmt.Println(f1 < f2) // false
fmt.Println(f1 == f2) // false
}
true false false