Removing unnecessary zeros from a BigDecimal instance

时间:2015-07-28 17:16:36

标签: java format scale precision bigdecimal

I've a simple program that adds two instances of BigDecimal:

public static void main(String[] args) {

    MathContext mathContext = new MathContext(32, RoundingMode.HALF_UP);
    System.out.println(new BigDecimal("999999999999999999999999999999").add(BigDecimal.ONE, mathContext));
    System.out.println(new BigDecimal("9999999999999999999999999999999").add(BigDecimal.ONE, mathContext));
    System.out.println(new BigDecimal("99999999999999999999999999999999").add(BigDecimal.ONE, mathContext));

}

It works perfectly fine. The output is:

1000000000000000000000000000000
10000000000000000000000000000000
1.0000000000000000000000000000000E+32

What I can't puzzle out is how to make the result look like:

1000000000000000000000000000000
10000000000000000000000000000000
1.E+32

How can I make the result get an ordinary appearance if the length is shorter than 32 digits, whereas if the result is longer, the outcome should have scientific notation but without unnecessary zeros at the end?

1 个答案:

答案 0 :(得分:2)

这可以通过不同方式完成,以下是我对您提问的建议:

public static void main(String[] args) {

    MathContext mathContext = new MathContext(32, RoundingMode.HALF_UP);
    BigDecimal[] bigDecimals =
         {
            new BigDecimal("999999999999999999999999999999").add(BigDecimal.ONE, mathContext),
            new BigDecimal("9999999999999999999999999999999").add(BigDecimal.ONE, mathContext),
            new BigDecimal("99999999999999999999999999999999").add(BigDecimal.ONE, mathContext)
         };

    for (int i = 0; i < bigDecimals.length; i++) {
        if ((bigDecimals[i]).toString().length() < 37) {
            System.out.println(bigDecimals[i]);
        } else {
            System.out.printf("%.1E\n", bigDecimals[i]);
        }
    }
}

输出结果如下所示:

1000000000000000000000000000000
10000000000000000000000000000000
1.0E+32

有趣的是通过将数字转换为字符串来计算数字的位数以进行检查(条件语句):

bigDecimals.toString().length()

另一件事是以上述/要求的格式打印:

System.out.printf("%.1E\n", bigDecimals);

<强>实施例
%E返回1.000000E+32
%.1E返回1.0E+32

您可以使用它来完成进一步的更改或要求。我把你的值放在数组和for loop中用于演示目的,这不应该吓到你。