Use of java.math.MathContext

前端 未结 5 1503
广开言路
广开言路 2020-12-08 13:18

Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 13:50

    If I'm understanding you correctly, it sounds like you're expecting the MathContext to control how many digits should be kept after the decimal point. That's not what it's for. It specifies how many digits to keep, total. So if you specify that you want 3 significant digits, that's all you're going to get.

    For example, this:

    System.out.println(new BigDecimal("1234567890.123456789",
                       new MathContext(20)));
    
    System.out.println(new BigDecimal("1234567890.123456789",
                       new MathContext(10)));
    
    System.out.println(new BigDecimal("1234567890.123456789",
                       new MathContext(5)));
    

    will output:

    1234567890.123456789
    1234567890
    1.2346E+9
    

提交回复
热议问题