Java BigDecimal-四舍五入到用户提供的多个
我有一个业务需求,输入值应该向下舍入到用户提供的倍数。以下是一个例子:Java BigDecimal-四舍五入到用户提供的多个,java,bigdecimal,Java,Bigdecimal,我有一个业务需求,输入值应该向下舍入到用户提供的倍数。以下是一个例子: 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
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
如果倍数为0.1,则输出应以0.1为增量,例如43.1、43.2等
如果倍数为0.2,则输出应以0.2为增量,例如43.0、43.2、43.4等
在Java中使用BigDecimal实现这一点的最佳方法是什么?使用BigDecimal.setScale1,舍入后我可以限制小数点的数量。一个简化的解决方案可以是伪代码
if (multiple == 0.1) then {
output = input
} else {
if ((int) input * 10 % 2 == 1) {
output -= 0.1
} else {
output = input
}
}
减去0.1后,需要注意舍入
编辑:可能的解决方案
请你把规则解释得更精确一点好吗。因为在5的情况下,输入值应该四舍五入+为零。。。增量值为0.2+输入向下舍入为43.0。首先你说它应该四舍五入,然后你提供了一个例子,在那里它被四舍五入。我现在更新了这个问题。0.1的四舍五入规则是没有意义的,因为输出总是等于输入。对于0.2,是否意味着四舍五入到0.2的最接近倍数?那么对于输入43.3,输出应该是43.2?什么倍数可能是0.3、0.4、3.5?如何处理输入43.21?倍数始终为0.1或0.2。是的,对于输入43.3和0.2,输出应该是43.2。是的,这是我的逻辑,但我想知道是否有更好的方法使用BigDecimal方法来实现这一点。@MFIhsan我添加了一个工作示例。看看这是否能满足您的需求。
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;
}
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