简体   繁体   中英

BigDecimal and MathContext

Can someone explain why those two have different results?

BigDecimal bd1 = new BigDecimal(1234.5678)
    .divide(
        new BigDecimal(1.19),
        4,
        RoundingMode.CEILING
    );
BigDecimal bd2 = new BigDecimal(1234.5678)
    .divide(
        new BigDecimal(1.19),
        new MathContext(4, RoundingMode.CEILING)
    );

Result :

bd1: 1037.4520
bd2: 1038

Because in MathContext(4, RoundingMode.CEILING) , 4 is precision, but in .divide(new BigDecimal(1.19), 4, RoundingMode.CEILING); , 4 is scale. You can see difference between "precision" and "scale" here

One important point that is alluded to but not directly addressed is the difference between " precision " and " scale " and how they are used in the two statements. " precision " is the total number of significant digits in a number. " scale " is the number of digits to the right of the decimal point.

So if you change second one to

final BigDecimal bd2 = new BigDecimal(1234.5678)
        .divide(
                new BigDecimal(1.19),
                new MathContext(8, RoundingMode.CEILING)
        );

You have same results:

1037.4520
1037.4520

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM