Manipulate price in inventory control

6

I'm doing a stock control system in Java and I came across a question about how to store prices. I've been reading that double and float are not good for storing this type of data and for a data loss when doing calculations with them. So what to wear?

    
asked by anonymous 26.03.2014 / 22:58

2 answers

7

How money management needs care really is not interesting to use floating points, because arithmetic operations with them result in certain #.

The recommended data type for this is BigDecimal , where you can choose the level of precision you want. Unlike double and float , which use the binary base and have problems storing fractional numbers, BigDecimal is more appropriate due to the fact that manipulations occur through the use of the decimal base.

Note: Due to the imprecision problems already mentioned, it is always recommended to make use of the constructor using String as a parameter, as in the example:

BigDecimal bd = new BigDecimal("0.1");
    
26.03.2014 / 23:07
2

As recommended by Martin Fowler in his Patterns of Enterprise Application Architecture book you should use:

An integer type with the amount (1000 = $ 10.00) The currency type (Reais or Dollars). You should avoid using any type of floating point as this may cause rounding problems which is what you want to avoid. In calculations you should always take into account the currency type.

Here has a page about the Martin Fowler standard

  

Retrieved from the book Martin Fowler Corporate Architectural Standards.

     

How It Works

     

The basic idea is to have a Money class with fields for the numeric quantity and the currency. You can store the quantity as an integer type or a fixed decimal type. The decimal type is easier for some manipulations, the integral for others. You should completely avoid any kind of floating point as this will introduce the kind of rounding problems whose purpose of Money is to avoid. Most of the time, people want monetary values rounded up to the smallest unit of the currency, like the cents on the dollar. However, there are times when fractional units are needed. It is important to make clear with what kind of money you are working, especially in an application that uses both types. It makes sense to have different types for the two cases, since they behave quite differently with respect to arithmetic.

    
27.03.2014 / 00:42