Java中BigDecimal類的add()的使用詳解
Java中的BigDecimal類的使用:
使用Java中的BigDecimal可以進行精確的計算,但是在使用BigDecimal時我們需要注意它的add()方法,使用它自身的add( )方法并不會改變它原始的值,因為初始化BigDecimal是創建一個了個對象,使用add()方法時也等于是創建了一個對象,若要保存這個對象需要再創建一個對象。
句法:
public BigDecimal add(BigDecimal val); public BigDecimal add(BigDecimal val, MathContext ma_co);
add() method is available in java.math package.
add()方法在java.math包中可用。
add(BigDecimal val) method is used to get a BigDecimal that holds the value added this BigDecimal with the given BigDecimal and its scale is calculated by using max([this BigDecimal.scale()] , [BigDecimal val.scale()]).
add(BigDecimal val)方法用于獲取一個BigDecimal,該BigDecimal保留使用給定BigDecimal與該BigDecimal相加的值,并使用max([thisBigDecimal.scale()],[BigDecimal val.scale()])計算其小數位數。
add(BigDecimal val, MathContext ma_co) method is used to get a BigDecimal that holds the value-added this BigDecimal with the given BigDecimal based on the given MathContext settings.
add(BigDecimal val,MathContext ma_co)方法用于獲取BigDecimal,該BigDecimal包含基于給定MathContext設置的給定BigDecimal與該BigDecimal的增值。
These methods may throw an exception at the time of adding an object.
這些方法在添加對象時可能會引發異常。
ArithmeticException: This exception may throw when the result is not accurate and set the rounding mode 'UNNECESSARY'.
ArithmeticException :當結果不正確并且將舍入模式設置為“ UNNECESSARY”時,可能會引發此異常。
These are non-static methods and it is accessible with class objects and if we try to access these methods with the class name then we will get an error.
這些是非靜態方法,可通過類對象訪問,如果嘗試使用類名訪問這些方法,則會收到錯誤消息。
使用BigDecimal的計算的錯誤示例:public static void main(String[]args){ double num1=19; double num2=20; //創建BigDecimal對象 BigDecimal bd1=new BigDecimal(Double.toString(num1)); BigDecimal bd1=new BigDecimal(Double.toString(num2)); //以add方法進行加運算 bd1.add(num2).doubleValue(); //輸出結果 System.out.printlin(bd1);//輸出19}使用BigDecimal的計算的正確示例:
public static void main(String[]args){ double num1=19; double num2=20; //創建BigDecimal對象 BigDecimal bd1=new BigDecimal(Double.toString(num1)); BigDecimal bd1=new BigDecimal(Double.toString(num2)); //以add方法進行加運算 bd1=bd1.add(num2).doubleValue(); //輸出結果 System.out.printlin(bd1);//輸出39}
綜上所述,當我們使用BigDecimal來計算時需要將它計算出的結果進行保存,若不進行操作,則原始值還是不變的。
到此這篇關于Java中BigDecimal類的add()的使用詳解的文章就介紹到這了,更多相關Java BigDecimal add()內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
