1

I am writing a function in which it should return the total amount that has been rounded to the nearest up pound (£). Note: the inputs are written as whole numbers without decimal places so 260 is actually £2.60 etc.

E.g.

intput: 260 -> output: 0.40

intput: 520 -> output: 0.80

total = 1.20 (because 40p + 80p)

I have written out this function:

public Double nearestPoundTotaler(List<Integer> transactions)
{
    double total = 0.00;

    for(Integer amount : transactions)
    {
        int penceAmount = amount % 100;
        int penceToNearestNextPound = 100 - penceAmount;
        double answer = penceToNearestNextPound / 100.0;
        total = total + answer;
    }
    return total;
}

I have written unit tests and the logic works but the test fails since the decimal places are incorrect. E.g. if passing 260,260,260 into the method, I get the following:

expected: 1.2

but was: 1.2000000000000002

I've tried numerous ways of removing the decimal place but I haven't seemed to find a way. Also is it possible to perform this logic with the .round() methods in Java?

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
tcho1506996
  • 105
  • 6
  • 2
    Does this answer your question? [Round a double to 2 decimal places](https://stackoverflow.com/questions/2808535/round-a-double-to-2-decimal-places) – op_ Oct 21 '21 at 20:07

1 Answers1

4

With the primitive type double you can't express exact numbers, due to numerical issues. Try using BigDecimal instead and the .divide() method. There you can also set the scale to 2 (2 decimal places) and the RoundingMode (usually HALF_UP)

retoen
  • 379
  • 1
  • 7