BigInteger divide method in Java with examples| BigDecimal divide tutorials
- Admin
- Mar 10, 2024
- Java-examples
This post shows how to divide BigInteger with others in Java with examples. You can also check my previous posts on the BigInteger
class in Java.
- BigInteger Class tutorials
- Convert BigInteger to/from BigDecimal
- Convert BigDecimal to/from String
- BigInteger Multiplication example
- Convert BigDecimal to float
- Convert BigDecimal to double
- Top 10 BigInteger Examples
- Rounding BigDecimal to 2 decimal places
- Check BigDecimal contains Zero or not
- Convert BigInteger to/from ByteArray
In java, long or integers can be divided using the division operator /
. However, BigInteger
can’t be divided, and throws an compilation error
Operator ’/’ cannot be applied to ‘java.math.BigInteger’, ‘java.math.BigInteger’.
Here is an example using the BigInteger division operator
import java.math.BigInteger;
public class BigIntegerDivisionOperator {
public static void main(String[] args) {
// Create two BigInteger
BigInteger operand1= BigInteger.valueOf(2);
BigInteger operand2= BigInteger.valueOf(2);
// Division throws an compilation error
BigInteger result=operand1/operand2;
System.out.println(result);
}
}
Java BigInteger Division method with example
The divide
method to divide BigInteger values, returns the result of the division of values
BigInteger is immutable, and the result returns a new object.
In Java, It uses an array of integers to do the process internally, The performance is less compared with the Integer division.
Syntax:
public BigInteger divide(BigInteger val)
This method called on the BigInteger object, takes the same type of parameter. Returns a new BigInteger object.
Here is an example of a BigInteger divide
import java.math.BigInteger;
public class BigIntegerMultiply {
public static void main(String[] args) {
// Create two operands of BigInteger values
BigInteger divident= BigInteger.valueOf(212312);
BigInteger divisor= BigInteger.valueOf(2123);
// Division
BigInteger result=divident.divide(divisor);
System.out.println(result);
}
}
Output:
100
How to divide two BigDecimals values into a BigDecimal object
divide
method always works with BigDecimal🔗 values.
First, Convert BigInteger into BigDecimal using the below code Next, use the divide
method and the result is BigDecimal
.
This method takes three parameter
- BigDecmal is the first parameter
- scale: the number of digits to the right of the decimal point
RoundingMode
is another parameter integer enum, contains HALF_UP
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigIntegerMultiply {
public static void main(String[] args) {
BigDecimal operand1= BigDecimal.valueOf(212312);
BigDecimal operand2= BigDecimal.valueOf(2123);
BigDecimal result=operand1.divide(operand2,4, RoundingMode.HALF_UP);
System.out.println(result);
}
}
Output:
100.0057