How to multiply a BigDecimal by an integer in Java

JavaBigdecimal

Java Problem Overview


How do you multiply a BigDecimal by an integer in Java? I tried this but its not correct.

import java.math.BigDecimal;
import java.math.MathContext;

public class Payment {
    int itemCost;
    int totalCost = 0;
    
    public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice){
        itemCost = itemPrice.multiply(itemQuantity);
        totalCost = totalCost + itemCost;
    return totalCost;
   }

Java Solutions


Solution 1 - Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
	BigDecimal itemCost  = BigDecimal.ZERO;
	BigDecimal totalCost = BigDecimal.ZERO;

	public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
		itemCost  = itemPrice.multiply(BigDecimal.valueOf(itemQuantity));
		totalCost = totalCost.add(itemCost);
		return totalCost;
	}
}

Solution 2 - Java

If I were you, I would set the scale of the BigDecimal so that I dont end up on lengthy numbers. The integer 2 in the BigDecimal initialization below sets the scale.

Since you have lots of mismatch of data type, I have changed it accordingly to adjust.

class Payment   
{
      BigDecimal itemCost=new BigDecimal(BigInteger.ZERO,  2);
      BigDecimal totalCost=new BigDecimal(BigInteger.ZERO,  2);

     public BigDecimal calculateCost(int itemQuantity,BigDecimal itemPrice)
       { 
	       BigDecimal	itemCost = itemPrice.multiply(new BigDecimal(itemQuantity)); 
             return totalCost.add(itemCost); 
       }
  }

BigDecimals are Object , not primitives, so make sure you initialize itemCost and totalCost , otherwise it can give you nullpointer while you try to add on totalCost or itemCost

Solution 3 - Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdeshView Question on Stackoverflow
Solution 1 - JavaJuvanisView Answer on Stackoverflow
Solution 2 - JavaJimmyView Answer on Stackoverflow
Solution 3 - JavapaxdiabloView Answer on Stackoverflow