简体   繁体   English

如何向 BigDecimal 添加额外的数字?

[英]How can i add extra digit to a BigDecimal?

In below code, user will enter firstAmount and secondAmount .在下面的代码中,用户将输入firstAmountsecondAmount Then program will run and do this calculation firstAmount*secondAmount/123 and answer will be in totalAmount variable.然后程序将运行并执行此计算firstAmount*secondAmount/123并且答案将在totalAmount变量中。 Further program will take the totalAmount and do some extra calculations, but before that i want to add extra digits to totalAmount .进一步的程序将采用totalAmount并进行一些额外的计算,但在此之前我想向totalAmount添加额外的数字。 For example if by calculating totalAmount gets amount something like 23.021 that is okay.例如,如果通过计算totalAmount得到类似23.021的金额,那没关系。 But it doesn't have any decimal point i would add that to it, for example if totalAmount gets amount 41 now there is no decimal point so i would add .00 means after that toalAmount will be 4.00 .但它没有任何小数点我会添加到它,例如,如果totalAmount得到金额41现在没有小数点,所以我会添加.00表示之后 toalAmount 将是4.00 How do i do that?我怎么做? How can i add extra digits if there is no already?如果还没有,我该如何添加额外的数字? Below is my code where i want this stuff to be happen.下面是我的代码,我希望这些事情发生。

switch (spinner.getSelectedItemPosition()){
    case 0:
    {
    
    totalAmount = firstAmount.multiply(secondAmount).divide(new BigDecimal("123"), MathContext.DECIMAL128);

   // before next calculation i want to add extra digits if there is no decimal point in the totalAmount

    nextCalculation = String.valueOf(totalAmount);
    
    break;
    }

You can always use setScale(int newScale, RoundingMode roundingMode) on BigDecimal to add decimal places.您始终可以在BigDecimal上使用setScale(int newScale, RoundingMode roundingMode)添加小数位。 Remember BigDecimal is immutable.请记住BigDecimal是不可变的。

if (totalAmount.scale() == 0) {
  totalAmount = totalAmount.setScale(2, RoundingMode.UNNECESSARY);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM