BigDecimal正在失去精确度

时间:2015-01-07 21:25:46

标签: java bigdecimal

我正在使用BigDecimal,它在打印速率和添加速率时会丢失精度。

import java.math.MathContext;
import java.math.BigDecimal;
public class Calc
{

    public static void main( String[] args ) {
        MathContext mc = new java.math.MathContext( 3 );

        double r = 1668.00;
        BigDecimal rate =   new BigDecimal( r,mc );
        BigDecimal taxWitholdingRate = new BigDecimal( 0.1185, new MathContext(4) );
        BigDecimal unitFrequency = new BigDecimal( 11.5,mc);

        System.out.println(   rate  );
        System.out.println(   taxWitholdingRate  );
        System.out.println(   unitFrequency  );


        BigDecimal serviceCost2 = new BigDecimal(0,mc);
        serviceCost2 = rate.multiply(taxWitholdingRate, mc  );  
        System.out.println(   serviceCost2  );
        serviceCost2  = serviceCost2.add( rate, mc);                        
        System.out.println(   (BigDecimal)serviceCost2 );
        serviceCost2 = serviceCost2.multiply(unitFrequency );
        System.out.println(   serviceCost2 );
    }    
}

java -cp。计算器
1.67E + 3
0.1185
11.5
198个
1.87E + 3
21505

1 个答案:

答案 0 :(得分:2)

假设这些应该是货币数字(到百分之一),我想你想使用BigDecimal.setScale(int, RoundingMode)之类的东西

public static void main(String[] args) {
    BigDecimal rate = new BigDecimal("1668.00");
    BigDecimal taxWitholdingRate = new BigDecimal("0.1185");
    BigDecimal unitFrequency = new BigDecimal("11.5");

    System.out.println(rate);
    System.out.println(taxWitholdingRate);
    System.out.println(unitFrequency);

    BigDecimal serviceCost2 = new BigDecimal("0");
    serviceCost2 = rate.multiply(taxWitholdingRate);
    System.out.println(serviceCost2.setScale(2, RoundingMode.HALF_UP));
    serviceCost2 = serviceCost2.add(rate);
    System.out.println(serviceCost2.setScale(2, RoundingMode.HALF_UP));
    serviceCost2 = serviceCost2.multiply(unitFrequency);
    System.out.println(serviceCost2.setScale(2, RoundingMode.HALF_UP));
}

输出

1668.00
0.1185
11.5
197.66
1865.66
21455.07