D
D
Dilik Pulatov2022-01-23 00:47:53
PostgreSQL
Dilik Pulatov, 2022-01-23 00:47:53

PostgreSQL - what is the best data type to use for currency?

In a project, the accuracy of the amount matters.
For example 123456789,000456 etc.
Wanted to use NUMERIC but read on the internet that NUMERIC values ​​are usually calculated slower than integers. And for the project, the speed of calculation is also important. What remains is real or double precision. Should they be used? Or is NUMERIC not so slower already?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Armenian Radio, 2022-01-23
@dilikpulatov

NEVER. NOT. SHOVEL. MONEY. IN NUMBERS. C. FLOATING. COMMA.
Because there are errors in floating point calculations that you can't explain to any accountant.
Use numeric, which was invented exactly, damn it, for this purpose.

And remember that premature optimization is often more trouble than it's worth.

M
Michael, 2022-01-23
@Akela_wolf

In general, if we talk about money, it is extremely unlikely that you will have fractions of kopecks (cents, etc.). Therefore, it is possible to store monetary amounts as a pair "integer" (long) + "currency code" (integer or string, ISO currency code). To this structure, then, you need to have a currency directory, in which there will be an accuracy of the currency, i.e. multiplier for transferring from rubles to kopecks, from dollars to cents, from euros to euro cents (1 to 100). And, for example, the yuan will have this multiplier 1, since these monetary units are not divided into shares. For Bitcoin, this multiplier will be 10^8 (Satoshi).
As a result, we get the opportunity to operate with monetary amounts as with integers, completely avoiding rounding errors.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question