天天看點

BigDecimal

一、源碼分析

二、注意問題

将<code>double</code>或者<code>float</code>資料轉換為<code>bigdecimal</code>類型,最好使用<code>bigdecimal.valueof()</code>,而不應該使用<code>new bigdecimal(double)</code>,因為:<code>new bigdecimal(0.1</code>)會把<code>0.1</code>當成: <code>0.1000000000000000055511151231257827021181583404541015625</code>,而<code>valueof</code>其内部使用了<code>string</code>作為構造函數的入參,是以使用valueof後<code>0.1</code>還是<code>0.1</code>

<code>system.out.println(2 / 0)</code> -&gt; <code>arithmeticexception: / by zero</code>

<code>system.out.println(2.0 / 0);</code> -&gt; <code>infinity</code>

看如下代碼,輸出是什麼?

在使用bigdecimal的equals方法對1和1.0進行比較的時候,有的時候是true(當使用int、double定義bigdecimal時),有的時候是false(當使用string定義bigdecimal時)

首先看equals方法的描述:<code>compares this bigdecimal with the specified object for equality. unlike compareto, this method considers two bigdecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method)</code>

意思是:equals方法和compareto并不一樣,equals方法會比較兩部分内容,分别是值(value)和精度(scale)

bigdecimal不同的構造函數,對應的精度是不同的

bigdecimal(long) 和bigdecimal(int):因為是整數,是以精度就是0;

bigdecimal(double):當我們使用<code>new bigdecimal(0.1)</code>建立一個bigdecimal 的時候,其實建立出來的值并不是整好等于0.1的,而是<code>0.1000000000000000055511151231257827021181583404541015625</code> 。這是因為doule自身表示的隻是一個近似值,那麼他的精度就是這個數字的位數,即55

bigdecimal(string):當我們使用<code>new bigdecimal("0.1")</code>建立一個bigdecimal 的時候,其實建立出來的值正好就是等于<code>0.1</code>的。那麼他的精度也就是1;如果使用<code>new bigdecimal("0.10000")</code>,那麼建立出來的數就是0.10000,精度也就是5。

bigdecimal中提供了compareto方法,這個方法就可以隻比較兩個數字的值,如果兩個數相等,則傳回0

别廢話,拿你代碼給我看。