代码:
BigDecimal bd = new BigDecimal( "99.11" );System.out.println( "scale=" + bd.scale() );System.out.println(bd);bd = new BigDecimal( 5526 );bd = bd.divide( new BigDecimal (1000) );System.out.println( "scale=" + bd.scale() );System.out.println(bd);System.out.println( "doubleValue=" + bd.doubleValue());bd = new BigDecimal( 23.256 );System.out.println( "--scale=" + bd.scale() );System.out.println(bd);System.out.println( "--doubleValue=" + bd.doubleValue());
运行结果:
结论:
1、如果传入的是字符串,则会自动计算“标度”,直接输出的字符串也是“精确的”
2、如果传入的是整数,且除以10 的 N 次幂,结果依然精确(即使是转换成 double)
3、如果传入的是 double,BigDecimal 内部保存的“标度”为45,转换回double 时原样输出。
设置精度( scale ) 和舍入方式:
static void testScale(){BigDecimal bd = new BigDecimal( 23/7.0 );System.out.println( "Before:" + bd.doubleValue() );double d = bd.setScale( 2, BigDecimal.ROUND_HALF_UP ).doubleValue();System.out.println( "After:" + d );}
输出:
Before:3.2857142857142856
After:3.29
注意:setScale( ) 方法会返回一个BigDecimal ,要对这个对象操作才有效。这是一个“ Value-Object”,每次操作返回一个新对象。
对没法精确表示的(除法),抛出异常
bd = new BigDecimal( 2655 );bd = bd.divide( new BigDecimal (122) );System.out.println( "scale=" + bd.scale() );System.out.println(bd);System.out.println( "doubleValue=" + bd.doubleValue());

DecimalFormat 格式化数字
示例
// . . . String formatNumber( BigDecimal number ){DecimalFormat decimalFormat = new DecimalFormat( "##.##" );decimalFormat.setMinimumFractionDigits( 2 );decimalFormat.setMaximumFractionDigits( 2 );String numberStr = decimalFormat.format( number );// 长度不够,补前导空格(如 "1.22" 应为 " 1.22")final int FORMAT_STRING_LENGTH = 5;if( numberStr.length() < FORMAT_STRING_LENGTH ){numberStr = addPreBlank( numberStr, FORMAT_STRING_LENGTH );}return numberStr;}String addPreBlank( String str, int formatLength ){assert str != null;assert !str.trim().equals("");assert str.length() < formatLength;final String ONE_BLANK = " ";int sub = formatLength - str.length();StringBuilder sb = new StringBuilder();for( int i = 0 ; i < sub ; i++ ){sb.append( ONE_BLANK );}return sb.toString() + str;}