Go Float Data Types

Go (Golang) – Floating-Point (Float) Data Types

Floating-point data types in Go are used to store decimal numbers (numbers with fractional parts).


1️⃣ Float Data Types in Go

Go provides two floating-point types:

Type Size Precision Use Case
float32 32-bit ~7 digits Memory-efficient
float64 64-bit ~15 digits High precision (default)
var a float32 = 3.14
var b float64 = 3.1415926535

2️⃣ Default Float Type

If no type is specified, Go uses float64 by default.

x := 9.99 // float64

✔ Recommended for most applications


3️⃣ Float Operations

a := 10.5
b := 3.2

fmt.Println(a + b) // Addition
fmt.Println(a - b) // Subtraction
fmt.Println(a * b) // Multiplication
fmt.Println(a / b) // Division


4️⃣ Float Formatting (Output)

Use formatting verbs with fmt.Printf().

price := 99.9999

fmt.Printf("%f\n", price) // 99.999900
fmt.Printf("%.2f\n", price) // 100.00


5️⃣ Type Conversion with Float

Go does not allow implicit conversion.

❌ Invalid:

var a int = 10
var b float64 = a // error

✅ Valid:

var b float64 = float64(a)

6️⃣ Float Comparison (⚠ Important)

Floating-point numbers may cause precision issues.

❌ Avoid:

fmt.Println(0.1 + 0.2 == 0.3) // false

✅ Better approach:

const eps = 0.00001
fmt.Println(math.Abs((0.1+0.2)-0.3) < eps)

(Requires import "math")


7️⃣ Math Functions with Float

import "math"

fmt.Println(math.Sqrt(16)) // 4
fmt.Println(math.Pow(2, 3)) // 8
fmt.Println(math.Round(3.6)) // 4


8️⃣ Special Float Values

fmt.Println(math.Inf(1)) // +Infinity
fmt.Println(math.NaN()) // Not a Number

9️⃣ Float vs Integer Division

fmt.Println(5 / 2) // 2 (int division)
fmt.Println(5.0 / 2.0) // 2.5 (float division)

🔟 Best Practices

✔ Use float64 by default
✔ Avoid direct equality comparison
✔ Use rounding/epsilon for comparisons
✔ Prefer integers for money (paise/cents)


Summary

  • Go supports float32 and float64

  • Default float type is float64

  • No implicit type conversion

  • Precision issues exist (handle carefully)

You may also like...