Table of Contents
In this tutorial we will see about BigDecimal‘s divide method. BigDecimal’s divide method is used to divide one BigDecimal by another. You can specify scale and rounding mode to get the output according to your need. There are 6 overloaded versions of divide method.
Syntax
1 2 3 4 5 6 7 8 |
BigDecimal divide ( BigDecimal divisor) BigDecimal divide ( BigDecimal divisor, int roundingMode) BigDecimal divide ( BigDecimal divisor,int scale, int roundingMode) BigDecimal divide ( BigDecimal divisor, int scale, RoundingMode roundingMode) BigDecimal divide ( BigDecimal divisor, MathContext mc) BigDecimal divide ( BigDecimal divisor, RoundingMode roundingMode) |
Return type
returns BigDecimal
BigDecimal round example
Let’s understand BigDecimal’s divide method with the help of example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.math.*; package org.arpit.java2blog; import java.math.BigDecimal; import java.math.RoundingMode; public class BigDecimalDivideMain { public static void main(String args[]) { BigDecimal b1=new BigDecimal("18"); BigDecimal b2=new BigDecimal("5"); BigDecimal result=b1.divide(b2); System.out.println("18/5 = "+result.toString()); // Using divide ( BigDecimal divisor, int scale, RoundingMode roundingMode) BigDecimal b3=new BigDecimal("17"); BigDecimal b4=new BigDecimal("3"); BigDecimal result1=b3.divide(b4,3,RoundingMode.HALF_UP); System.out.println("17/3 = "+result1.toString()); } } |
Above program will generate below output.
18/5 = 3.6
17/3 = 5.667
17/3 = 5.667
Please be careful when you use divide method.Please check if divisor is zero or not before dividing otherwise you will get divide by zero exception.
That’s all about BigDecimal’s divide method.
You may also like:
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.