當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java BigDecimal shortValueExact()用法及代碼示例


java.math.BigDecimal.shortValueExact()是Java中的一種內置方法,可將BigDecimal轉換為簡短形式,以檢查丟失的信息。如果此BigDecimal的分數部分非零或超出可能的範圍,則可能會拋出ArithmeticException。

用法:

public short shortValueExact()

參數:該方法不接受任何參數。


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

以下示例程序旨在說明上述方法:
示例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()



相關用法


注:本文由純淨天空篩選整理自Twinkl Bajaj大神的英文原創作品 BigDecimal shortValueExact() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。