Sobes.tech
Middle+

Why is float not suitable for working with money?

sobes.tech AI

Answer from AI

The float type (floating-point numbers) is not suitable for working with money due to limited precision in representing decimal fractions. In computers, floating-point numbers are stored in binary format, and many decimal fractions cannot be represented exactly, leading to rounding errors.

For financial calculations, accuracy up to the cent is important, and even small errors can cause significant problems. Instead of float, the following are usually used:

  • Integer types that store the amount in minimal units (e.g., kopecks).
  • Specialized fixed-point decimal types (decimal, big.Rat in Go).

Example in Go using int64 to store the amount in kopecks:

var priceInCents int64 = 1999 // 19.99 rubles
var quantity int64 = 3
var total int64 = priceInCents * quantity // 5997 kopecks
fmt.Printf("Total: %d.%02d rubles", total/100, total%100)

This approach eliminates rounding errors typical for float.