Java BigDecimal shortValueExact() Method with Example

BigDecimal Class shortValueExact() method: Here, we are going to learn about the shortValueExact() method of BigDecimal Class with its syntax and example.
Submitted by Preeti Jain, on May 07, 2020

BigDecimal Class shortValueExact() method

  • shortValueExact() method is available in java.math package.
  • shortValueExact() method is used to convert this BigDecimal to an exact short value.
  • shortValueExact() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • shortValueExact() method may throw an exception at the time of converting BigDecimal to a short.
    ArithmeticException: This exception may throw when this BigDecimal holds a fractional part that is other than 0 or the resulting value is not enough to adjust in a short.

Syntax:

    public short shortValueExact();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is short, it returns the short representation of this BigDecimal.

Example:

// Java program to demonstrate the example 
// of short shortValueExact() method of BigDecimal

import java.math.*;

public class ShortValueExactOfBD {
    public static void main(String args[]) {
        // Initialize two variables of int and 
        // String type
        int val = 1245;
        String str = "100";

        // Initialize two BigDecimal objects  
        BigDecimal b_dec1 = new BigDecimal(val);
        BigDecimal b_dec2 = new BigDecimal(str);

        // converts this BigDecimal b_dec1
        // into a short, and store in a variable named s_conv
        short s_conv = b_dec1.shortValueExact();
        System.out.println("b_dec1.shortValueExact(): " + s_conv);

        // converts this BigDecimal b_dec2
        // into a short, and store in a variable named s_conv
        s_conv = b_dec2.shortValueExact();
        System.out.println("b_dec2.shortValueExact(): " + s_conv);
    }
}

Output

b_dec1.shortValueExact(): 1245
b_dec2.shortValueExact(): 100


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.