Search code examples
javabigdecimal

Java BigDecimal - rounding down to the user-provided multiple


I have a business requirement where the input values should be rounded down to the multiples provided by user. Here is the example:

Case | input | multiples | output
1    | 43.0  | 0.1       | 43.0
2    | 43.1  | 0.1       | 43.1
3    | 43.2  | 0.1       | 43.2
4    | 43.0  | 0.2       | 43.0
5    | 43.1  | 0.2       | 43.0
6    | 43.2  | 0.2       | 43.2

If the multiples is 0.1, then the output should be in the increments of 0.1, e.g., 43.1, 43.2, etc.

If the multiples is 0.2, then the output should be in the increments of 0.2, e.g., 43.0, 43.2, 43.4, etc.

What is the best way to do this in Java using BigDecimal? Using BigDecimal.setScale(1, ROUND_DOWN) I was able to restrict the number of decimal points though.


Solution

  • A simplified solution could be (pseudo code)

    if (multiple == 0.1) then {
        output = input
    } else {
        if ((int) input * 10 % 2 == 1) {
            output -= 0.1
        } else {
            output = input
        }
    }
    

    You need to take care about the rounding after you substract 0.1.

    edit: possible solution

    double input = 43.0;
    for (int i = 0; i <= 10; i++) {
        double output = input;
        if ((int) (input * 10) % 2 == 1) {
            output = ((double) (int) (input * 10) - 1) / 10;
        }
        System.out.printf("input:  %f   output: %f%n", input, output);
        input += 0.1;
    }
    

    resulting output

    input:  43.000000   output: 43.000000
    input:  43.100000   output: 43.000000
    input:  43.200000   output: 43.200000
    input:  43.300000   output: 43.200000
    input:  43.400000   output: 43.400000
    input:  43.500000   output: 43.400000
    input:  43.600000   output: 43.600000
    input:  43.700000   output: 43.600000
    input:  43.800000   output: 43.800000
    input:  43.900000   output: 43.800000
    input:  44.000000   output: 44.000000