Float or decimal for prices?

前端 未结 5 1384
误落风尘
误落风尘 2020-12-28 17:49

Which type (Float or decimal) is best used to store prices in a mysql database?

相关标签:
5条回答
  • 2020-12-28 18:26

    Please Use BigDecimal , as it is the best for the prices , since pennies are rounded properly to dollar.

    Joshua Bloch recommends BigDecimal.

    0 讨论(0)
  • 2020-12-28 18:35

    Prices are decimal values, and calculations on them are expected to behave like decimal fractions when it comes to rounding, literals, etc.

    That's exactly what decimal types do.

    Floats are stored as binary fractions, and they do not behave like decimal fractions - their behaviour is frequently not what people used to decimal math expect. Read The Floating-Point Guide for detailed explanations.

    For money values, never never use binary float types - especially when you have a perfectly good decimal type available!

    0 讨论(0)
  • 2020-12-28 18:46

    For Financial calculations use Decimal

    According to IEEE 754 Floats were always binary, only the new standard IEEE 754R defined decimal formats. Many of the fractional binary parts can never equal the exact decimal representation. Any binary number can be written as m/2^n (m, n positive integers), any decimal number as m/(2^n*5^n). As binarys lack the prime factor 5, all binary numbers can be exactly represented by decimals, but not vice versa.

    0.3 = 3/(2^1 * 5^1) = 0.3
    
    0.3 = [0.25/0.5] [0.25/0.375] [0.25/3.125] [0.2825/3.125]
    
         1/4       1/8     1/16       1/32
    

    So for Financial calculations use Decimal not FLOAT

    0 讨论(0)
  • 2020-12-28 18:48

    When we store a number in float we don't save the exact number,it is an approximation. The integer part gets the priority and fractional part is as close as the type size. So if you have calculations and need accurate result use Decimal.

    0 讨论(0)
  • 2020-12-28 18:52

    Floats are not exact and can introduce cumulative rounding errors. Decimal is the best format for financial information that must be exact.

    0 讨论(0)
提交回复
热议问题