Handle price in stock control

Asked

Viewed 338 times

7

I’m making a stock control system in Java and came across a question about how to store prices. I’ve been reading that double and float are not good to store this kind of data and about a data loss while doing calculations with them. So, what to use?

  • you will make currency conversion?

  • No, I will store the values to show in tables, conducting promotions etc

2 answers

8


As money manipulation needs care it is really not interesting to use floating points, because arithmetic operations with them result in certain inaccuracies.

The data type recommended for this is the Bigdecimal, where you can choose the desired accuracy level. Unlike the double and of float, using the binary basis and having trouble keeping fractional numbers, the BigDecimal is more appropriate due to the fact that manipulations occur through the use of decimal basis.

Note: due to the problems of imprecision 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");

4

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

An integer type with the amount (1000 = R$ 10.00) The currency type (Real 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 the calculations you should always take into account the currency type.

Here has page on the pattern of Martin Fowler

Taken from the book Corporate Architectural Patterns by Martin Fowler.

How It Works

The basic idea is to have a Money class with fields for numerical quantity and 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 type 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 to the smallest unit of the currency, like the pennies on the dollar. However, there are times when fractional units are needed. It is important to make clear what kind of money you are working with, especially in an application that uses both types. It makes sense to have different types for both cases, as they behave quite differently with regard to arithmetic.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.