Sobes.tech
Middle

What type of data should be used to store monetary amounts to avoid rounding errors?

sobes.tech AI

Answer from AI

It is better to use a fixed-precision data type for storing monetary amounts, such as decimal or numeric (depending on the language and DBMS). These types store numbers with exact decimal representation and are not susceptible to rounding errors characteristic of floating-point numbers (float, double).

Example in Python using decimal:

from decimal import Decimal

price = Decimal('19.99')
tax = Decimal('0.07')
total = price + price * tax
print(total)  # Will output the exact value without rounding errors

In databases, such as PostgreSQL, the numeric(precision, scale) type is used for monetary amounts, where precision is the total number of digits, and scale is the number of digits after the decimal point.

What type of data should be used to store monetary… - sobes.tech