Comparing numbers
I have the following lines in a code:
System.out.println(9000000000000000d == 9000000000000001d);
System.out.println(90000000000000000d == 90000000000000001d);
The results are:
false
true
That's strange... someone knows why this happen ? And how can I compare big numbers like this correctly ?
[337 byte] By [
dragzula] at [2007-11-26 13:18:47]

In double range, the number is, but even using BigDecimal, that's what happened:
BigDecimal a = new BigDecimal(90000000000000000d);
BigDecimal b = new BigDecimal(90000000000000001d);
System.out.println(a.equals(b));
The result is:
true
I'll take a look for "java floating point innacuracy"... anyway, I'll be waiting if I'll get an answer by here.
> In double range, the number is, but even using
> BigDecimal, that's what happened:
>
> BigDecimal a = new BigDecimal(90000000000000000d);
> BigDecimal b = new BigDecimal(90000000000000001d);
> System.out.println(a.equals(b));
>
> The result is:
>
> true
That's because you're still using doubles in the constructor. Use the BigDecimal constructor that takes a String instead, then you obviate length limitations.
If I'll take out the "d", it'll be out of range.
But what I wan't is compare double numbers, and big numbers, really. I've put BigDecimal after indications. If it works, I'll find a way. If I use String, maybe it'll work, but I don't know... I'm looking for some performance, because I want to compare and calculate numbers bigger than the range of Long, so, I'll try to find another way.
If there's no other, I'll pass a String... thanks everybody !!