BigDecimal比較大小
這個類是java裏精確計算的類,下面說一下兩個BigDecimal對象大小,相等的判斷
1 比較對象是否相等
一般的對象用equals,但是BigDecimal比較特殊,舉個例子:
BigDecimal a=BigDecimal.valueOf(1.0);
BigDecimal b=BigDecimal.valueOf(1.000);
在現實中這兩個數字是相等的,但是問題來來了
a.equals(b)結果是false;怎麼不相等了呢?這個問題我也不知道
解決辦法:
if(a.compareTo(b)==0)結果是true
public int compareTo(BigDecimal val)
Compares this BigDecimal with the specified BigDecimal.
Two BigDecimal objects that are equal in value but have a different
scale (like 2.0 and 2.00) are considered equal by this method.
This method is provided in preference to individual methods for each of
the six boolean comparison operators (<, ==, >, >=, !=, <=).
The suggested idiom for performing these comparisons is: (x.compareTo(y) <op> 0), where <op> is one of the six comparison operators.
Specified by:
compareTo in interface Comparable<BigDecimal>
Parameters:
val - BigDecimal to which this BigDecimal is to be compared.
Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.
簡單翻譯:
結果是-1 小於
0 等於
1 大於
java BigDecimal比較大小
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.