0

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;
    }
  • do you mean you want to set the scale of the BigDecimal? – jhamon Jul 24 '20 at 07:38
  • No, I want to add decimal point to the `totalAmount` if there is no decimal point already . –  Jul 24 '20 at 07:42
  • Why does `41` become `4.00`? –  Jul 24 '20 at 07:46
  • Does this answer your question? [How to display a number with always 2 decimal points using BigDecimal?](https://stackoverflow.com/questions/14515640/how-to-display-a-number-with-always-2-decimal-points-using-bigdecimal) – Amongalen Jul 24 '20 at 07:47

1 Answers1

5

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);
}
raupach
  • 3,092
  • 22
  • 30
  • 3
    I think you can use `.setScale(2)` just fine, no need to specify RoundingMode. – Amongalen Jul 24 '20 at 07:53
  • Problem is we cannot use variable outside if else . What to do ? My code is focusing on first variable which is `totalAmount = firstAmount.multiply(secondAmount).divide(new BigDecimal("123"), MathContext.DECIMAL128);` and not on if else. –  Jul 24 '20 at 08:02