0

我有如下要求。

我有许多 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

有没有最简单的解决方案?

谢谢!

4

1 回答 1

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());
于 2012-07-25T11:38:21.397 回答