Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply a BigDecimal by an integer in Java

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;    } 
like image 201
Adesh Avatar asked Oct 17 '12 22:10

Adesh


People also ask

How do I convert BigDecimal to integer?

intValue()converts this BigDecimal to an int. This conversion is analogous to the narrowing primitive conversion from double to short. Any fractional part of this BigDecimal will be discarded, and if the resulting "BigInteger" is too big to fit in an int, only the low-order 32 bits are returned.

Can we convert BigDecimal to double in Java?

math. BigDecimal. doubleValue() is an in-built function which converts the BigDecimal object to a double. This function converts the BigDecimal to Double.

Is BigDecimal same as double?

A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001 ) could result in the 0.001 being dropped alltogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.


1 Answers

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;     } } 
like image 165
Juvanis Avatar answered Oct 11 '22 12:10

Juvanis