Decimal places of the float

Asked

Viewed 2,992 times

15

I am developing an application to control product sales. However, sometimes the added value of reports does not beat decimal places. Gives small differences. How to make the float stop giving these problems? I always use only two decimal places on float and sometimes it puts more alone. I would like in a way that the float was only with two decimal places and in sales reports always calculated correctly. It is possible?

2 answers

16


With the float there’s nothing to do. I’ve essentially answered in that reply (has several links to other information, I recommend reading all, especially those that are in English, if you can). This seems to be one of the most common problems encountered in novice (and even experienced programmers).

float cannot be used to work with money, it lacks precision and is not because it lacks decimal places, could have 30 million decimal places and would still have problems. The difficulty is how it is calculated and represented. It’s very fast for being binary but it can’t represent all the possible numbers, so the number you want to store possibly will be represented by another number very close to what you want. This is not a problem in most scientific calculations but is impractical for money.

The float can be shown with two decimal places but it always has several houses in its representation. And again, this is not what causes the problem.

And there’s no point in using double. Not even a superdouble, or halffloat if they existed. It will probably only create more problem.

The correct is the use of Decimal which is the simplest solution and is usually very efficient. Or some library to deal specifically with Money or the Official API for money which is a bit inferior (it seems that comes a new API in Java 9, do not know if it solves the problem). Beware, these libraries can be exaggerated for what you need. These guys work with decimal accuracy, that is, they can represent any number without error.

Ex.: BigDecimal bd = new BigDecimal("123.45");

Care must be taken anyway, these classes do not solve all problems alone.

To string is used to avoid rounding problems since Java does not have a literal for decimal types.

  • Thank you. I’ll study the decimal.

  • The link to the "new API in Java 9" is broken.

  • @Piovezan put another

12

As answered above, using Decimal usually solves your floating point usage problem in Java.

I would just like to share a technique that I learned in the 1980s working with languages that didn’t have this kind of data: multiply the monetary values by 100 and convert them to integer. Make the necessary sums and subtractions and in the end divide the result by 100.

As in practice you have worked all the time with integers, there should be no differences...

  • Exactly, it works too. In the other answer I pointed out I say this.

Browser other questions tagged

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