Middle+
How to solve the problem with float for monetary operations?
sobes.tech AI
Answer from AI
The problem with using float for monetary operations is related to loss of precision due to the characteristics of floating-point representation.
To avoid errors when working with money, the following approaches are usually used:
- Use integer types to store amounts in minimal units (for example, kopecks or cents). For example, instead of 10.50, store 1050.
- Use specialized libraries for decimal arithmetic (decimal), which provide accurate calculations without rounding errors.
In Go, you can use the math/big package with the big.Rat type or third-party libraries for decimal arithmetic.
Example using the integer approach:
package main
import "fmt"
func main() {
var priceInCents int64 = 1050 // 10.50 rubles
var quantity int64 = 3
total := priceInCents * quantity
fmt.Printf("Total: %d kopecks\n", total) // 3150 kopecks = 31.50 rubles
}