Home > OS >  Removing to 2 decimal places
Removing to 2 decimal places

Time:10-22

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 found a way. Also is it possible to perform this logic with the .round() methods in Java?

CodePudding user response:

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)

CodePudding user response:

Multiply your result by 100, parse it to an Integer, divide it by hundred and parse it back to a double.

int temp = (int)(total * 100.0);
double finalValue = (double)(temp / 100.0);
  • Related