-3

Opinions on reliability/viability of doing something like this to workaround IEEE oddities in addition and subtraction etc...? I want to avoid BigDecimal,Formatters,etc... GC overhead

exploring this idea.

int fivePlaces = 100000;
Assert.assertEquals(1.13269, add(1.13270, -0.00001, fivePlaces), 0);

private double add(double aPrice,
                   double aModifier,
                   double aPrecision) {
    long price = (long) (aPrice * aPrecision);
    long modifier= (long) (aModifier * aPrecision);
    long adjustedPrice = price + modifier;
    return adjustedPrice / aPrecision;
}

for example:

    double d = 1.30784;
    double d2 = -0.00005;
    double d3 = d + d2;
    double d4 = add(d, d2, 100000);
    System.out.println(d3);
    System.out.println(d4);

the idea is to avoid this result: 1.3077899999999998

and get this one: 1.30778

with primitives.

andmer
  • 9

1 Answers1

5

The number 1.30778 cannot be represented exactly as a double. For this number, the most accurate representation will be 0x3FF4ECAAB8A5CE5B which is 1.30777999999999994251709267701.

The core problem with this is do not use a double to store money. Any use of a floating point number will inherently have problems with monetary amounts.

Suck it up and use a BigDecimal.

See also: