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

huangapple go评论74阅读模式
英文:

How can i add extra digit to a BigDecimal?

问题

在下面的代码中,用户将输入firstAmountsecondAmount。然后程序将运行并进行如下计算:firstAmount*secondAmount/123,答案将保存在totalAmount变量中。接下来,程序将使用totalAmount进行一些额外的计算,但在此之前我想在totalAmount上添加额外的数字。例如,如果通过计算得到的totalAmount金额为23.021,那就可以了。但是,如果没有小数点,我希望添加它。例如,如果totalAmount得到了41,现在没有小数点,所以我想添加.00,这意味着totalAmount将变为41.00。我该怎么做?如何在没有小数点的情况下添加额外的数字?以下是我希望进行此操作的代码:

switch (spinner.getSelectedItemPosition()){
    case 0: {
        totalAmount = firstAmount.multiply(secondAmount).divide(new BigDecimal("123"), MathContext.DECIMAL128);
        
        // 在进行下一次计算之前,如果totalAmount中没有小数点,我想添加额外的数字
        if (totalAmount.scale() == 0) {
            totalAmount = totalAmount.setScale(2); // 添加两位小数
        }

        nextCalculation = String.valueOf(totalAmount);

        break;
    }
}
英文:

In below code, user will enter firstAmount and secondAmount. Then program will run and do this calculation firstAmount*secondAmount/123 and answer will be in totalAmount variable. Further program will take the totalAmount and do some extra calculations, but before that i want to add extra digits to totalAmount. For example if by calculating totalAmount gets amount something like 23.021 that is okay. 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. 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;
    }

答案1

得分: 5

你可以始终在 BigDecimal 上使用 setScale(int newScale, RoundingMode roundingMode) 来增加小数位。请记住,BigDecimal 是不可变的。

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

You can always use setScale(int newScale, RoundingMode roundingMode) on BigDecimal to add decimal places. Remember BigDecimal is immutable.

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

huangapple
  • 本文由 发表于 2020年7月24日 15:36:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63068957.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定