PostgreSQL: Which Datatype should be used for Currency?

前端 未结 6 805
盖世英雄少女心
盖世英雄少女心 2020-11-27 10:56

Seems like Money type is discouraged as described here

My application needs to store currency, which datatype shall I be using? Numeric, Money or FLOAT?

6条回答
  •  暖寄归人
    2020-11-27 11:48

    Your choices are:

    1. bigint : store the amount in cents. This is what EFTPOS transactions use.
    2. decimal(12,2) : store the amount with exactly two decimal places. This what most general ledger software uses.
    3. float : terrible idea - inadequate accuracy. This is what naive developers use.

    Option 2 is the most common and easiest to work with. Make the precision (12 in my example, meaning 12 digits in all) as large or small as works best for you.

    Note that if you are aggregating multiple transactions that were the result of a calculation (eg involving an exchange rate) into a single value that has business meaning, the precision should be higher to provide a accurate macro value; consider using something like decimal(18, 8) so the sum is accurate and the individual values can be rounded to cent precision for display.

提交回复
热议问题