参考文章链接:http://www.opentaps.org/docs/index.php/How_to_Use_Java_BigDecimal:_A_Tutorial
*************************************************************************以下是对该技术文章的总结***********************************************************************************
简略介绍下BigDecimal 作用: 能够在程序运算中控制:运算数、运算结果的小数精度;按何种规则舍入运算数。
BigDecimal example:
一、 BigDecimal 构造示例
1、double参数的BigDecimal例子:
bd = new BigDecimal(1.5);
bd.toString(); // => 0.1499999999999999944488848768742172978818416595458984375
2、String入参例子:
bd = new BigDecimal("1.5");
3、以下例子中,设置它的舍入位数:
<pre name="code" class="java">bd = new BigDecimal(1.5); // is actually 1.4999....
bd.setScale(1); // throws ArithmeticException
但是很不幸,抛异常。原因:他不知道该按照怎样的舍入规则。利用方法: .setScale(scale, roundingMode),就阔以了。
bd = new BigDecimal(1.5); // is actually 1.4999....
bd.setScale(1, RoundingMode.HALF_UP);
二、介绍8中舍入规则
ROUND_CEILING: Ceiling function
0.333 -> 0.34 -0.333 -> -0.33
ROUND_DOWN: Round towards zero
0.333 -> 0.33 -0.333 -> -0.33
ROUND_FLOOR: Floor function
0.333 -> 0.33 -0.333 -> -0.34
ROUND_HALF_UP: Round up if decimal >= .5
0.5 -> 1.0 0.4 -> 0.0
ROUND_HALF_DOWN: Round up if decimal > .5
0.5 -> 0.0 0.6 -> 1.0ROUND_HALF_EVEN: 前提是舍入数字为5,它左边是偶数就向下舍入;如果为奇数,向上舍入。可自行做测试!
a = new BigDecimal("2.5"); // digit left of 5 is even, so round down b = new BigDecimal("1.5"); // digit left of 5 is odd, so round up a.setScale(0, BigDecimal.ROUND_HALF_EVEN).toString() // => 2 b.setScale(0, BigDecimal.ROUND_HALF_EVEN).toString() // => 2ROUND_UNNECESSARY:
Use ROUND_UNNECESSARY when you need to use one of the methods that requires input of a rounding mode but you know the result won't need to be rounded.
文章提了下 bigdecimal 中的除法运算,详情:
When dividing BigDecimals, be careful to specify the rounding in the .divide(...) method. Otherwise, you could run into an ArithmeticException if there is no precisely rounded resulting value, such as 1/3. Thus, you should always do:
a = b.divide(c, decimals, rounding);就是说,如果两数相除,如果最终的结果是个无线循环的小数,不要忘记告诉程序要舍入位数以及该使用何种舍入规则。
三、使用bigdecimal 注意点(对于bigdecimal做基本运算时,都会产生一个新的对象,这个新的对象里才包含运算结果!):
So how do we do math then? The methods .add(), .multiply(), and so on all return a new BD value containing the result. For example, when you want to keep a running total of the order amount,
amount = amount.add( thisAmount );
Make sure you don't do this,
amount.add( thisAmount );
THIS IS THE MOST COMMON MISTAKE MADE WITH BIGDECIMALS!
四、两个bigdecimal比较BigDecimal a = new BigDecimal("2.00"); BigDecimal b = new BigDecimal("2.0"); print(a.equals(b)); // false
Instead, we should use the .compareTo() and .signum() methods.
a.compareTo(b); // returns (-1 if a < b), (0 if a == b), (1 if a > b) a.signum(); // returns (-1 if a < 0), (0 if a == 0), (1 if a > 0)