英文:
How can i add extra digit to a BigDecimal?
问题
在下面的代码中,用户将输入firstAmount
和secondAmount
。然后程序将运行并进行如下计算: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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论