Java BigDecimal shortValueExact()方法

Java BigDecimal shortValueExact()方法

java.math.BigDecimal.shortValueExact() 是java中的一个内置方法,可以将BigDecimal转换为short,并检查是否有丢失的信息。如果这个BigDecimal有一个非零的小数部分,或者超出了短值结果的可能范围,那么就会抛出一个ArithmeticException。

语法

public short shortValueExact()

参数: 该方法不接受任何参数。

返回值: 该方法返回BigDecimal对象的短值。

下面的程序说明了上述的方法:

程序1 :

// Program to demonstrate shortValueExact() method of BigDecimal 
  
import java.math.*;
  
public class gfg {
  
    public static void main(String[] args)
    {
  
        BigDecimal b1 = new BigDecimal("457");
        BigDecimal b2 = new BigDecimal("4785");
  
        // Assigning the short value of BigDecimal objects b1 and b2
        // to short s1, s2 respectively
        short s1 = b1.shortValueExact();
        short s2 = b2.shortValueExact();
  
        // Printing s1, s2 values
        System.out.println("Exact short value of " + b1 + " is " + s1);
        System.out.println("Exact short value of " + b2 + " is " + s2);
    }
}

输出。

Exact short value of 457 is 457
Exact short value of 4785 is 4785

程序2

// Program to demonstrate shortValueExact() method of BigDecimal 
  
  
import java.math.*;
  
public class gfg {
  
    public static void main(String[] args)
    {
  
        BigDecimal b1 = new BigDecimal("127");
        BigDecimal b2 = new BigDecimal("1455");
  
        // assign the short value of BigDecimal objects b1 and b2
        // to short s1, s2 respectively
        short s1 = b1.shortValueExact();
        short s2 = b2.shortValueExact();
  
        // print s1, s2 values
        System.out.println("Exact short value of " + b1 + " is " + s1);
        System.out.println("Exact short value of " + b2 + " is " + s2);
    }
}

输出。

Exact short value of 127 is 127
Exact short value of 1455 is 1455

参考资料 : https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#shortValueExact()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程