简体   繁体   English

Java BigDecimal - 向下舍入到用户提供的多个

[英]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, eg, 43.1, 43.2, etc. 如果multiples为0.1,则输出应为0.1的增量,例如43.1,43.2等。

If the multiples is 0.2, then the output should be in the increments of 0.2, eg, 43.0, 43.2, 43.4, etc. 如果multiples为0.2,则输出应为0.2的增量,例如43.0,43.2,43.4等。

What is the best way to do this in Java using BigDecimal ? 使用BigDecimal在Java中执行此操作的最佳方法是什么? Using BigDecimal.setScale(1, ROUND_DOWN) I was able to restrict the number of decimal points though. 使用BigDecimal.setScale(1, ROUND_DOWN)我能够限制小数点的数量。

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. 在减去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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM