Multiply BigDecimal by int in Java - Java Examples code

Overview

In this tutorial, we show you how to multiply BigDecimal Object by primitive data type such as int. The example below demonstrates multiplication of two numbers(ex: productPrice as BigDecimal and quantity as int).

Multiply BigDecimal by int in Java

How to multiply a BigDecimal by int

The following example shows you how to multiply BigDecimal Object by int.
package com.jackrutorial;

import java.math.BigDecimal;
import java.math.BigInteger;

public class MultiplyBigdecimalByIntExample {

 public static void main(String[] args) {
  //price = $22.19
  BigDecimal productPrice = new BigDecimal("22.19");
  System.out.println("Product Cost‎ = $" + productPrice);
  
  //Quantity = 2
  int quantity = 2;
  System.out.println("Quantity = " + quantity);
  
  //Amount
  BigDecimal amount = new BigDecimal(BigInteger.ZERO,  2);
  
  BigDecimal totalCost = productPrice.multiply(new BigDecimal(quantity));
  amount = amount.add(totalCost);
  
  System.out.println("---------------------");
  System.out.println("Amout = $" + amount);
 }
}
In the code snippet above, we calculate the cost of product by multiplying the cost of each item with quantity (totalCost = productPrice*quantity). First, we initialize amount (BigDecimal) as 0 for a default value
BigDecimal amount = new BigDecimal(BigInteger.ZERO,  2);
Second, We convert quantity (int) to BigDecimal Object.
new BigDecimal(quantity)
Finally, we multiply two BigDecimal numbers (productPrice*quantity) using BigDecimal.multiply() method and add it to totalCost variable.
BigDecimal totalCost = productPrice.multiply(new BigDecimal(quantity));
amount = amount.add(totalCost);
Run the application and output to the console is as shown below

Output

Product Cost‎ = $22.19
Quantity = 2
---------------------
Amout = $44.38
Previous Post
Next Post

post written by: