Java.math.BigDecimal.shortValueExact() 方法



描述

java.math.BigDecimal.shortValueExact() 将此 BigDecimal 转换为一个 short,并检查丢失的信息。如果此 BigDecimal 具有非零小数部分或超出 short 结果的可能范围,则会抛出 ArithmeticException。

声明

以下是 java.math.BigDecimal.shortValueExact() 方法的声明。

public short shortValueExact()

```java

参数

不适用

返回值

此方法返回 BigDecimal 对象的 short 值。

异常

ArithmeticException - 如果小数部分非零或不适合 short。

示例

package com.tutorialspoint;

import java.math.*;

public class BigDecimalDemo {

   public static void main(String[] args) {

      // create 2 BigDecimal objects
      BigDecimal bg1, bg2;

      // create 2 short objects
      short s1, s2;

      bg1 = new BigDecimal("235");
      bg2 = new BigDecimal("4364");

      // assign the short value of bg1 and bg2 to s1,s2 respectively
      s1 = bg1.shortValueExact();
      s2 = bg2.shortValueExact();

      String str1 = "Exact short value of " + bg1 + " is " + s1;
      String str2 = "Exact short value of " + bg2 + " is " + s2;

      // print s1,s2 values
      System.out.println( str1 );
      System.out.println( str2 );
   }
}

现场演示

Exact short value of 235 is 235
Exact short value of 4364 is 4364
让我们编译并运行以上程序,它将产生以下结果 -
打印页面
© . All rights reserved.