Home Java Java-bigdecimal Java divide method example


Share on Google+Share on Google+

Java divide method example

In this example Java bigdecimal class divide (BigDecimal divisor, MathContext mc) method working is demonstrated.

Java divide method example


In this example Java bigdecimal class divide (BigDecimal divisor, MathContext mc) method working is demonstrated. This method divides this.object value by the specified object value & returns quotient as per defined context settings. Scale of the quotient is this.scale, which is the scale of the object in which the method is invoked.

 Example contains three MathContext class objects mc_0, mc_1 and mc_2 respectively and three different  MathContext class static fields DECIMAL32, DECIMAL64 & DECIMAL128 respectively.  Static fields used are MathContext class,  predefined objects that have their own format and rounding mode  settings defined in them.  Method throws Arithmetic Exception in following cases : 

If the Rounding mode is UNNECESSARY, ie mc.precision == 0, when the divisor value is zero, when the specified rounding mode does not represent a valid rounding mode, and when a non-terminating quotient is generated.

Method throws NumberFormatException if it finds a value other than a integer or double value. 

Syntax for using the method:

System.out.println(bigdecimal_objectName.divide(BigDecimal divisor, MathContext mc)); 
BigDecimal x = this.object.divide(divisor, mc);


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

 public class Java_BigDecimal_divide_BigDecimal_divisor_MathContext_mc {
 public static void main(String args[]) {
 MathContext mc_0 = new MathContext(0),
  mc_1 = new MathContext(0),
  mc_2 = new MathContext(0);

 mc_0 = MathContext.DECIMAL32;
 mc_1 = MathContext.DECIMAL64;
 mc_2 = MathContext.DECIMAL128;
 int Dividend = 57, Divisor = 7;
 BigDecimal rose = new BigDecimal(57),
 neo = new BigDecimal(7)
 Quotient = new BigDecimal(0);
 /*The constructor BigDecimal(BigDecimal)
 is undefined*/
 Quotient = rose.divide(neo, mc_0);
 System.out.println("Quotient as per context settings : "
 + Quotient + "\nRemainder : " + Dividend % Divisor);
 Quotient = rose.divide(neo, mc_1);
 System.out.println("Result as per context settings : "
 + Quotient + "\nRemainder : " + Dividend % Divisor);
 Quotient = rose.divide(neo, mc_2);
 System.out.println("Result as per context settings : "
 +  Quotient + "\nRemainder : " + Dividend % Divisor);

Download the code


If you enjoyed this post then why not add us on Google+? Add us to your Circles

Liked it!  Share this Tutorial

Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 21, 2008

Related Tutorials

Ask Questions?    Discuss: Java divide method example  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image