I bet there was a similar question here on SO, I just could not find it.
The question is about fixing java math inaccuracy, when I get for example a number like 235.00000002
or 9875.999999997
. Sure as a hell, for a human these two actually mean 235
and 9876
, when a certain accuracy threshold is given, let's call it "5 zeros or nines".
But it's not only about the digits to the right of the decimal point, the same rule should also apply to numbers like 23500000001.0
and 5699999999.0
Any ideas/libraries?
Update:
Looks like I was wrong saying it's a known topic and a matter of minutes until someone pops up with a known library. So here is the logic I expect:
For a given number when N consecutive zeroes or nines are encountered in its string representation, then these zeroes and nines are rounded together with the rest of the number to the right of the rightmost "0" or "9".
Foe example, when N=5, then the number 239999995.546
becomes 240000000.0
, the number 34.0000007
becomes 34
as well as 340000.007
becomes 340000
.
Update 2:
That's what happens when in a hurry or paying not enough attention to the question. Sorry. I'm talking about "human" rounding. A good example would be comparing the output of df
and df -h
on a linux box. As for "inaccuracy" I was talking about, please run the following code:
double d = 1000.0;
double mult = 0.12351665;
System.out.println(d * mult / mult);
The response is definitely not the one you'd show in a shopping cart. In my case the situation is even worse, it's not only the money I deal with, it can be anything - percentage, big numbers, small fractions, and all of them as a result of relatively heavy math computations. So I'm talking about the rounding that makes sense for a human.
I'm already done with the code, but there is still a chance that someone did it better.