0

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.

MFIhsan
  • 1,037
  • 3
  • 15
  • 35
  • Could you please explain the rule a bit more precise. Because `input values should be rounded off` + `in case of #5 ... increment values as 0.2` + `the input is rounded down to 43.0`. First you say it should be rounded off and then you provide an example where it is rounded down. – SubOptimal Mar 06 '15 at 06:39
  • The rounding rule for `0.1` is meaningless, as output would be always equal to the input. Does it for `0.2` mean round down to the nearest multiple of `0.2`? So for input `43.3` the output should be `43.2`? What multiples are possible `0.3, 0.4, 3.5`? How to handle input `43.21`? – SubOptimal Mar 06 '15 at 07:37
  • Multiples are always 0.1 or 0.2. Yes, for input 43.3 and 0.2, output should be 43.2. – MFIhsan Mar 06 '15 at 07:41

1 Answers1

0

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
SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • Yes, that's the logic I have, but I was wondering if there was any better way of doing this using BigDecimal methods. – MFIhsan Mar 06 '15 at 08:35
  • @MFIhsan I add a working example. Have a look if this might be a solution for your requirement. – SubOptimal Mar 06 '15 at 09:04