In this tutorial, we will learn about the float32 data type in Go. We will cover the basics of defining and using float32 values, including how to perform arithmetic operations and format floating-point numbers.
The float32
data type in Go is used to represent 32-bit floating-point numbers. It is suitable for applications where memory usage is a concern, but it provides less precision than float64
.
Float32 variables in Go can be defined using the var
keyword or by type inference.
var f1 float32 = 3.14
f2 := float32(2.718)
Arithmetic operations such as addition, subtraction, multiplication, and division can be performed on float32 values.
sum := f1 + f2
difference := f1 - f2
product := f1 * f2
quotient := f1 / f2
Float32 values can be formatted for output using the fmt
package.
fmt.Printf("%.2f", f1)
We can define and use float32 variables in Go to represent 32-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 float32 = 3.14
f2 := float32(2.718)
fmt.Println(f1)
fmt.Println(f2)
}
3.14 2.718
We can perform arithmetic operations on float32 values in Go.
For example,
f1
and f2
.package main
import "fmt"
func main() {
f1 := float32(3.14)
f2 := float32(2.718)
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.858 Difference: 0.422 Product: 8.53452 Quotient: 1.1553134
We can format float32 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 float32 value with two decimal places.package main
import "fmt"
func main() {
f := float32(3.14159)
fmt.Printf("%.2f\n", f)
}
3.14
We can compare float32 values in Go using relational operators.
For example,
f1
and f2
with different values.package main
import "fmt"
func main() {
f1 := float32(3.14)
f2 := float32(2.718)
fmt.Println(f1 > f2) // true
fmt.Println(f1 < f2) // false
fmt.Println(f1 == f2) // false
}
true false false