Junior — Middle
How is it recommended to organize the storage of price data in a database?
sobes.tech AI
Answer from AI
To store price data in a database, it is recommended to use fixed-point data types to avoid rounding errors characteristic of floating-point numbers.
In most DBMSs, including PostgreSQL and MySQL, the DECIMAL or NUMERIC type is used with specified precision and scale, for example DECIMAL(10,2), where 10 is the total number of digits and 2 is the number of digits after the decimal point.
Example:
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
price DECIMAL(10,2) NOT NULL
);
This approach guarantees precise storage of monetary values and is convenient for financial calculations.
It is also important to store prices in the smallest units (for example, in kopecks or cents) as integers if acceptable for the application, to simplify arithmetic and avoid rounding issues.