Метод BigDecimal divAndRemainder () в Java с примерами

Опубликовано: 7 Февраля, 2022

Java.math.BigDecimal .divideAndRemainder (делитель BigDecimal) используется для вычисления как частного, так и остатка от двух BigDecimals. Если требуются как целое частное, так и остаток, этот метод работает быстрее, чем использование методов divToIntegralValue () и Остаток () по отдельности, поскольку деление необходимо выполнять только один раз. Этот метод выполняет операцию над текущим BigDecimal, с помощью которого этот метод вызывается и BigDecimal передается в качестве параметра.

В Java доступны две перегрузки метода divAndRemainder, которые перечислены ниже:

  • divAndRemainder (делитель BigDecimal)
  • divAndRemainder (делитель BigDecimal, MathContext mc)

divAndRemainder (делитель BigDecimal)

Синтаксис:

public BigDecimal [] divAndRemainder (делитель BigDecimal)

Параметры: этот метод принимает делитель параметра, по которому этот BigDecimal должен быть разделен для получения остатка и частного.
Возвращаемое значение: этот метод возвращает массив BigDecimal размера два, который содержит частное и остаток .
Исключение: делитель параметра не должен быть равен 0, в противном случае возникает арифметическое исключение.

Below programs is used to illustrate the divideAndRemainder() method of BigDecimal.

// Java program to demonstrate
// divideAndRemainder() method of BigDecimal
  
import java.math.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res[];
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Two objects of String created
        // Holds the values
        String input1
            = "456865265569";
        String input2
            = "65245";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
        BigDecimal divisor
            = new BigDecimal(input2);
  
        // Using divideAndRemainder() method
        res = a.divideAndRemainder(divisor);
  
        // Display the result in BigDecimal
        System.out.println("Quotient = " + res[0]
                           + " Remainder = " + res[1]);
    }
}
Output:
Quotient = 7002303
Remainder = 6334

Reference: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divideToIntegralValue(java.math.BigDecimal)

divideAndRemainder(BigDecimal divisor, MathContext mc)

This method is used to calculate the quotient which is the result of divideToIntegralValue() followed by the result of remainder() on the two operands calculated with rounding according to the context settings.

Syntax:

public BigDecimal[] divideAndRemainder(BigDecimal divisor, 
                                       MathContext mc)

Parameters: This method accepts two parameters:

  • divisor by which this BigDecimal is to be divided
  • mc of type MathContext for context settings.

Return value: This method returns a BigDecimal array of size two, which holds the quotient and remainder.

Exception: The method throws Arithmetic Exception for following conditions:

  • If the parameter divisor is 0.
  • If the result is inexact but the rounding mode is UNNECESSARY or mc.precision > 0 and the result of this.divideToIntgralValue(divisor) would require a precision of more than mc.precision digits.

Below programs is used to illustrate the divideAndRemainder() method of BigDecimal.
Program 1:

// Java program to demonstrate
// divideAndRemainder() method of BigDecimal
  
import java.math.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res[];
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Two objects of String created
        // Holds the values
        String input1
            = "4568652655";
        String input2
            = "2562";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
        BigDecimal divisor
            = new BigDecimal(input2);
  
        // Set precision to 10
        MathContext mc
            = new MathContext(10);
  
        try {
            // Using divideAndRemainder() method
            res = a.divideAndRemainder(divisor, mc);
  
            // Display the result in BigDecimal
            System.out.println("Quotient = " + res[0]
                               + " Remainder = " + res[1]);
        }
        catch (Exception e) {
  
            System.out.println(e);
        }
    }
}
Output:
Quotient = 1783236
Remainder = 2023

Program 2: Program showing exception thrown by method divideAndRemainder().

// Java program to demonstrate
// divideAndRemainder() method of BigDecimal
  
import java.math.*;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res[];
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Two objects of String created
        // Holds the values
        String input1
            = "4568652655";
        String input2
            = "2562";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
        BigDecimal divisor
            = new BigDecimal(input2);
  
        // Set precision to 5
        MathContext mc
            = new MathContext(5);
  
        try {
            // Using divideAndRemainder() method
            res = a.divideAndRemainder(divisor, mc);
  
            // Display the result in BigDecimal
            System.out.println("Quotient = " + res[0]
                               + " Remainder = "
                               + res[1]);
        }
        catch (Exception e) {
  
            System.out.println(e);
        }
    }
}
Output:
java.lang.ArithmeticException: Division impossible

References: https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/math/BigDecimal.html#divideAndRemainder(java.math.BigDecimal, java.math.MathContext)

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Next
BigDecimal remainder() method in Java with Examples
Recommended Articles
Page :
Article Contributed By :
Rajnis09
@Rajnis09
Vote for difficulty
Article Tags :
  • Java-BigDecimal
  • Java-Functions
  • Java-math-package
  • Java
Practice Tags :
  • Java
Report Issue
Java

РЕКОМЕНДУЕМЫЕ СТАТЬИ