位置:首頁 > Java技術 > Java.math包 > Java.math.BigDecimal.shortValueExact()方法實例

Java.math.BigDecimal.shortValueExact()方法實例

java.math.BigDecimal.shortValueExact() 此BigDecimal 轉換為short,檢查丟失的信息。如果此BigDecimal具有非零小數部分,或者short的結果超出的可能範圍,那麼則拋出ArithmeticException。

聲明

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

public short shortValueExact()

參數

  • NA

返回值

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

異常

  • ArithmeticException - 如果這具有非零小數部分,或者將不適合使用short

例子

下麵的例子顯示math.BigDecimal.shortValueExact()方法的用法

package com.yiibai;

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