Java BigDecimal:四舍五入为客户首选数字并递增
Java BigDecimal: Rounding off to client preferred digits and increment
我需要根据客户偏好对某些值进行四舍五入。客户可以自定义位数和四舍五入值,如下所示。
NumOfDigits | RoundOff | InputValue || ExpectedOutput
0.01 | 2 | 43.0 || 43.0
0.01 | 2 | 43.1 || 43.1
0.01 | 2 | 43.11 || 43.11
0.01 | 2 | 43.11234 || 43.11
0.1 | 1 | 43.0 || 43.0
0.1 | 1 | 43.1 || 43.1
0.1 | 1 | 43.12 || 43.1
0.1 | 1 | 43.1234 || 43.1
0.2 | 1 | 43.0 || 43.0
0.2 | 1 | 43.1 || 43.0
0.2 | 1 | 43.2 || 43.2
0.2 | 1 | 43.3 || 43.2
0.2 | 1 | 43.11 || 43.0
0.3 | 1 | 43.0 || 43.0
0.3 | 1 | 43.1 || 43.0
0.3 | 1 | 43.2 || 43.0
0.3 | 1 | 43.3 || 43.3
0.3 | 1 | 43.11 || 43.0
0.25 | 2 | 33.0 || 33.0
0.25 | 2 | 33.3 || 33.25
0.25 | 2 | 33.7 || 33.50
0.25 | 2 | 33.9 || 33.75
0.25 | 2 | 33.33 || 33.25
0.25 | 2 | 33.71 || 33.50
0.25 | 2 | 33.91 || 33.75
0.25 | 2 | 33.12345 || 33.25
我可以使用以下代码限制位数。但是,我找不到按照上述逻辑四舍五入的解决方案。
BigDecimal incrementedValue = BigDecimal.valueOf(inputValue).setScale(numOfDigits, ROUND_DOWN);
根据维基百科 (http://en.wikipedia.org/wiki/Rounding#Rounding_to_a_specified_increment),将数字 x 舍入为某个增量 m 的倍数需要以下过程:
Rounded value z = round(x, m) = round(x / m) * m
在您的情况下,您希望始终向下舍入。这是通过使用地板而不是圆形来实现的。翻译成 Java,您的程序将如下所示。
// ex. input = 33.91, increment = 0.25 -> 33.75
public double round(double input, double increment) {
return Math.floor(input / increment) * increment;
}
我需要根据客户偏好对某些值进行四舍五入。客户可以自定义位数和四舍五入值,如下所示。
NumOfDigits | RoundOff | InputValue || ExpectedOutput
0.01 | 2 | 43.0 || 43.0
0.01 | 2 | 43.1 || 43.1
0.01 | 2 | 43.11 || 43.11
0.01 | 2 | 43.11234 || 43.11
0.1 | 1 | 43.0 || 43.0
0.1 | 1 | 43.1 || 43.1
0.1 | 1 | 43.12 || 43.1
0.1 | 1 | 43.1234 || 43.1
0.2 | 1 | 43.0 || 43.0
0.2 | 1 | 43.1 || 43.0
0.2 | 1 | 43.2 || 43.2
0.2 | 1 | 43.3 || 43.2
0.2 | 1 | 43.11 || 43.0
0.3 | 1 | 43.0 || 43.0
0.3 | 1 | 43.1 || 43.0
0.3 | 1 | 43.2 || 43.0
0.3 | 1 | 43.3 || 43.3
0.3 | 1 | 43.11 || 43.0
0.25 | 2 | 33.0 || 33.0
0.25 | 2 | 33.3 || 33.25
0.25 | 2 | 33.7 || 33.50
0.25 | 2 | 33.9 || 33.75
0.25 | 2 | 33.33 || 33.25
0.25 | 2 | 33.71 || 33.50
0.25 | 2 | 33.91 || 33.75
0.25 | 2 | 33.12345 || 33.25
我可以使用以下代码限制位数。但是,我找不到按照上述逻辑四舍五入的解决方案。
BigDecimal incrementedValue = BigDecimal.valueOf(inputValue).setScale(numOfDigits, ROUND_DOWN);
根据维基百科 (http://en.wikipedia.org/wiki/Rounding#Rounding_to_a_specified_increment),将数字 x 舍入为某个增量 m 的倍数需要以下过程:
Rounded value z = round(x, m) = round(x / m) * m
在您的情况下,您希望始终向下舍入。这是通过使用地板而不是圆形来实现的。翻译成 Java,您的程序将如下所示。
// ex. input = 33.91, increment = 0.25 -> 33.75
public double round(double input, double increment) {
return Math.floor(input / increment) * increment;
}