Float decimal places

15

I'm developing an application to track product sales. However, sometimes the added value of reports does not beat the decimal places. It gives small differences. How do float stop giving these problems? I always use only two decimal places in float and sometimes it puts more alone. I would like a way that float would only have two decimal places and in the sales reports I would always calculate correct. Is it possible?

    
asked by anonymous 11.11.2014 / 13:02

2 answers

15

With float there is nothing to do. Essentially I've already replied in this answer (there are several links to other information, I recommend reading all, especially those in English, if you can). This seems to be one of the most common problems found in novice (and even experienced) programmers.

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

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

And it's no use using double . Not even a superdouble

11.11.2014 / 13:12
12

As stated above, using Decimal typically solves your Java floating-point problem.

I would just like to share a technique I learned in the 1980s working with languages that did not 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 worked with integers all the time, there should be no differences ...

    
12.11.2014 / 02:12