天天看點

BigDecimal類的簡單使用方法

一提到Java裡面的商業計算,我們都知道不能用float和double,由于他們無法進行精确計算。可是Java的設計者給程式設計人員提供了一個非常實用的類BigDecimal,他能夠完好float和double類無法進行精确計算的缺憾。BigDecimal類位于java.maths類包下。首先我們來看下怎樣構造一個BigDecimal對象。它的構造函數非常多,我挑最經常使用的兩個來示範一下:一個就是BigDecimal(double val),還有一個就是BigDecimal(String str)。這兩個看上去沒什麼太大差别,可是正像API描寫叙述中說的那樣:

/*The results of this constructor can be somewhat unpredictable. One might assume that

new BigDecimal(.1) is exactly equal to .1, but it is actually equal

to .1000000000000000055511151231257827021181583404541015625. This is so because .1

cannot be represented exactly as a double (or, for that matter, as a binary fraction

of any finite length). Thus, the long value that is being passed in to the constructor

is not exactly equal to .1, appearances nonwithstanding.

The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal

(".1") is exactly equal to .1, as one would expect. Therefore, it is generally

recommended that the (String) constructor be used in preference to this one.*/

也就是說利用double作為參數的構造函數,無法精确構造一個BigDecimal對象,須要自己指定一個上下文的環境,也就是指定精确位。而利用String對象作為參數傳入的構造函數能精确的構造出一個BigDecimal對象。請看以下的代碼:

import java.math.*;

public class TestBigDecimal {

public static void main(String args[]){

BigDecimal bd = new BigDecimal("10.123");

BigDecimal bd1 = new BigDecimal(10.123);

System.out.println(bd +"/n"+ bd1);

}

輸出:

10.123

是以我們在選擇構造函數時,要看詳細需求而定。

另外,非常多人會問到怎麼将基本類型,如int,float,double,long,和BigDecimal對象互相轉換。非常easy:

基本類型通過構造函數轉換成相應的BigDecimal對象,而BigDecimal類提供了諸如intValue(), floatValue(), doubleValue(), longValue()方法來将BigDecimal對象轉換成相應的值。

關于BigDecimal是怎樣計算的,我以論壇中一個人的提問文章為例,來簡單的寫出BigDecimal的運算方法。題目是:李白無事街上走,提壺去買酒。遇店加一倍,見花喝一鬥,五遇花和店,喝光壺中酒,試問李白壺中原有多少鬥酒?

這道題應該是從後往前推,而且要逆運算,最後得出原有酒的體積。

public class Libai {

BigDecimal volumn = new BigDecimal("0");

for (int i=0; i<5; i++){

volumn = volumn.add(new BigDecimal("1"));

volumn = volumn.divide(new BigDecimal("2"));

System.out.print(volumn);

結果:

0.96875