Java中BigDecimal類(lèi)的add()的使用詳解
Java中的BigDecimal類(lèi)的使用:
使用Java中的BigDecimal可以進(jìn)行精確的計(jì)算,但是在使用BigDecimal時(shí)我們需要注意它的add()方法,使用它自身的add( )方法并不會(huì)改變它原始的值,因?yàn)槌跏蓟疊igDecimal是創(chuàng)建一個(gè)了個(gè)對(duì)象,使用add()方法時(shí)也等于是創(chuàng)建了一個(gè)對(duì)象,若要保存這個(gè)對(duì)象需要再創(chuàng)建一個(gè)對(duì)象。
句法:
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)方法用于獲取一個(gè)BigDecimal,該BigDecimal保留使用給定BigDecimal與該BigDecimal相加的值,并使用max([thisBigDecimal.scale()],[BigDecimal val.scale()])計(jì)算其小數(shù)位數(shù)。
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設(shè)置的給定BigDecimal與該BigDecimal的增值。
These methods may throw an exception at the time of adding an object.
這些方法在添加對(duì)象時(shí)可能會(huì)引發(fā)異常。
ArithmeticException: This exception may throw when the result is not accurate and set the rounding mode 'UNNECESSARY'.
ArithmeticException :當(dāng)結(jié)果不正確并且將舍入模式設(shè)置為“ UNNECESSARY”時(shí),可能會(huì)引發(fā)此異常。
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.
這些是非靜態(tài)方法,可通過(guò)類(lèi)對(duì)象訪問(wèn),如果嘗試使用類(lèi)名訪問(wèn)這些方法,則會(huì)收到錯(cuò)誤消息。
使用BigDecimal的計(jì)算的錯(cuò)誤示例:public static void main(String[]args){ double num1=19; double num2=20; //創(chuàng)建BigDecimal對(duì)象 BigDecimal bd1=new BigDecimal(Double.toString(num1)); BigDecimal bd1=new BigDecimal(Double.toString(num2)); //以add方法進(jìn)行加運(yùn)算 bd1.add(num2).doubleValue(); //輸出結(jié)果 System.out.printlin(bd1);//輸出19}使用BigDecimal的計(jì)算的正確示例:
public static void main(String[]args){ double num1=19; double num2=20; //創(chuàng)建BigDecimal對(duì)象 BigDecimal bd1=new BigDecimal(Double.toString(num1)); BigDecimal bd1=new BigDecimal(Double.toString(num2)); //以add方法進(jìn)行加運(yùn)算 bd1=bd1.add(num2).doubleValue(); //輸出結(jié)果 System.out.printlin(bd1);//輸出39}
綜上所述,當(dāng)我們使用BigDecimal來(lái)計(jì)算時(shí)需要將它計(jì)算出的結(jié)果進(jìn)行保存,若不進(jìn)行操作,則原始值還是不變的。
到此這篇關(guān)于Java中BigDecimal類(lèi)的add()的使用詳解的文章就介紹到這了,更多相關(guān)Java BigDecimal add()內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單2. 小技巧處理div內(nèi)容溢出3. JavaWeb Servlet中url-pattern的使用4. 使用XSL將XML文檔中的CDATA注釋輸出為HTML文本5. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案6. jsp實(shí)現(xiàn)簡(jiǎn)單用戶(hù)7天內(nèi)免登錄7. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向8. XML入門(mén)的常見(jiàn)問(wèn)題(一)9. PHP循環(huán)與分支知識(shí)點(diǎn)梳理10. chat.asp聊天程序的編寫(xiě)方法
