我有如下要求。向BigDecimal号码加1的精度?
我有很多的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
有没有什么简单的解决方案?
谢谢!
我有如下要求。向BigDecimal号码加1的精度?
我有很多的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
有没有什么简单的解决方案?
谢谢!
您可以重新调整它,加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());
或者你可以添加'BigDecimal.ONE.scaleByPowerOfTen(-scale)' – 2012-07-25 11:49:44
@PeterLawrey:是的,听起来好多了。编辑。 – Keppil 2012-07-25 11:52:19
@Keppil,谢谢你的回复。如果下面的行被执行:System.out.println(increaseBy1(new BigDecimal(“100.9”)));输出将是101.0。但我期待100.10。谢谢! – user1538040 2012-07-25 12:08:34
它总是增加.1至任何数量?如果你通过100.01,它会返回100.02或100.11? – 2012-07-25 11:27:09
它应该返回100.02而不是100.11。谢谢! – user1538040 2012-07-25 11:28:14
100.012 100.022或100.013应该是什么结果? – Pshemo 2012-07-25 11:31:23