我的要求如下。
我有一些BigDecimal类型:100
i need a method which will take input(100 here) and gives output as 100.1
if 100.1 is passed it should return 100.2
if 100.2 is passed it should return 100.3....etc
有最简单的解决方案吗?
谢谢!
答案 0 :(得分:4)
您可以重新缩放它,添加1,然后缩小它。
正如@PeterLawrey建议的那样,这可以简化为仅添加BigDecimal.ONE.scaleByPowerOfTen(-scale)
。
public static BigDecimal increaseBy1(BigDecimal value) {
int scale = value.scale();
return value.add(BigDecimal.ONE.scaleByPowerOfTen(-scale));
}
public static void main(String[] args) {
System.out.println(increaseBy1(new BigDecimal("100.012")));
System.out.println(increaseBy1(new BigDecimal("100.01")));
System.out.println(increaseBy1(new BigDecimal("100.1")));
System.out.println(increaseBy1(new BigDecimal("100")));
}
打印
100.013
100.02
100.2
101
如果您希望100
成为100.1
,请将第一行更改为
int scale = Math.max(1, value.scale());