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

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

Java.math.BigDecimal .setScale () используется для установки масштаба BigDecimal. Этот метод выполняет операцию с текущим BigDecimal, с помощью которого вызывается этот метод.

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

  • setScale (интервал newScale)
  • setScale (интервал newScale, интервал roundingMode)
  • setScale (интервал newScale, RoundingMode roundingMode)

Примечание . SetScale (int newScale, int roundingMode) устарел, начиная с Java 9 .

setScale (интервал newScale)

Этот вызов обычно используется для увеличения масштаба, когда гарантировано, что существует BigDecimal указанного масштаба и правильного значения. Вызов также можно использовать для уменьшения масштаба, если пользователь знает, что BigDecimal имеет достаточно много нулей в конце дробной части, чтобы можно было изменить масштаб без изменения его значения.
Синтаксис:

public BigDecimal setScale(int newScale)

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

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

// Java program to demonstrate
// setScale() method of BigDecimal
  
import java.math.BigDecimal;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res;
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Object of String created
        // Holds the value
        String input1
            = "31452678569.25";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Scale for BigDecimal
        int newScale = 4;
  
        // Using setScale() method
        res = a.setScale(newScale);
  
        // Display the result in BigDecimal
        System.out.println(res);
    }
}
Output:
31452678569.2500

setScale(int newScale, int roundingMode)

This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.
Syntax:

public BigDecimal setScale(int newScale, int roundingMode)

Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode to set the rounding value of result.
Return value: This method returns a BigDecimal whose scale is of the specified value.
Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding. This method also throws IllegalArgumentException if roundingMode does not represent a valid rounding mode.

Below programs is used to illustrate the setScale() method of BigDecimal.
Example 1:

// Java program to demonstrate
// setScale() method of BigDecimal
  
import java.math.BigDecimal;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res;
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Object of String created
        // Holds the value
        String input1
            = "31452678569.24";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Scale for BigDecimal
        int newScale = -1;
        try {
  
            // Using setScale() method
            res = a.setScale(newScale, 1);
  
            // Display the result in BigDecimal
            System.out.println(res);
        }
        catch (Exception e) {
  
            // Print Exception
            System.out.println(e);
        }
    }
}
Output:
3.145267856E+10

Example 2: Program showing Exceptions thrown by this method.



// Java program to demonstrate
// setScale() method of BigDecimal
  
import java.math.BigDecimal;
  
public class GFG {
    public static void main(String[] args)
    {
        // BigDecimal object to store the result
        BigDecimal res;
  
        // For user input
        // Use Scanner or BufferedReader
  
        // Object of String created
        // Holds the value
        String input1
            = "31452678569.24";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Scale for BigDecimal
        int newScale = -1;
  
        try {
  
            // Using setScale() method
            res = a.setScale(newScale, 7);
  
            // Display the result in BigDecimal
            System.out.println(res);
        }
        catch (Exception e) {
  
            // Print Exception
            System.out.println(e);
        }
  
        try {
  
            // Using setScale() method
            res = a.setScale(newScale, 10);
  
            // Display the result in BigDecimal
            System.out.println(res);
        }
        catch (Exception e) {
  
            // Print Exception
            System.out.println(e);
        }
    }
}
Output:
java.lang.ArithmeticException: Rounding necessary
java.lang.IllegalArgumentException: Invalid rounding mode

setScale(int newScale, RoundingMode roundingMode)

This method is used to calculate a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal’s unscaled value by the appropriate power of ten to maintain its overall value. If the scale is reduced by the operation then unscaled value must be divided (rather than multiplied). The specified rounding mode is applied to the division.
Syntax:

public BigDecimal setScale(int newScale, RoundingMode roundingMode)

Parameters: This method accepts two parameter newScale which is used to set the scale of this BigDecimal and roundingMode of type RoundingMode that tells which rounding mode to apply.
Return value: This method returns a BigDecimal whose scale is of the specified value.
Exception: The method throws Arithmetic Exception if roundingMode is UNNECESSARY and the specified scaling operation would require rounding.

Below programs is used to illustrate the setScale() method of BigDecimal.
Example 1:

// Java program to demonstrate
// setScale() 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
  
        // Object of String created
        // Holds the value
        String input1
            = "31452678569.24";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Scale for BigDecimal
        int newScale = 1;
  
        try {
  
            // Using setScale() method
            // Using RoundingMode.CEILING
            res = a.setScale(newScale, RoundingMode.CEILING);
  
            // Display the result in BigDecimal
            System.out.println(res);
        }
        catch (Exception e) {
  
            // Print Exception
            System.out.println(e);
        }
    }
}
Output:
31452678569.3

Example 2: Program showing Exceptions thrown by this method.

// Java program to demonstrate
// setScale() 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
  
        // Object of String created
        // Holds the value
        String input1
            = "31452678569.24";
  
        // Convert the string input to BigDecimal
        BigDecimal a
            = new BigDecimal(input1);
  
        // Scale for BigDecimal
        int newScale = -1;
  
        try {
  
            // Using setScale() method
            // Using RoundingMode.UNNECESSARY
            res = a.setScale(newScale, RoundingMode.UNNECESSARY);
  
            // Display the result in BigDecimal
            System.out.println(res);
        }
        catch (Exception e) {
  
            // Print Exception
            System.out.println(e);
        }
    }
}
Output:
java.lang.ArithmeticException: Rounding necessary

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

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 scale() Method in Java
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

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