short shortValueExact()

优质
小牛编辑
130浏览
2023-12-01

描述 (Description)

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

声明 (Declaration)

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

public short shortValueExact()

参数 (Parameters)

NA

返回值 (Return Value)

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

异常 (Exception)

ArithmeticException - 如果它具有非零小数部分,或者不适合短。

例子 (Example)

以下示例显示了math.BigDecimal.shortValueExact()方法的用法。

package cn.xnip;
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