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?