javaprecisionscalebigdecimaldigits

BigDecimal - How to know the precision in small decimal numbers below 1 considering left zeroes just after comma


I am developing a calculator and I want to format the number in scientific notation only when it reaches a certain number of digits.

I wrote this piece of code which works fine for big numbers.

DecimalFormat df;
if (valorSaida.stripTrailingZeros().precision() > FOCalcConstants.MAX_DIGITOS) {
    df = new DecimalFormat("0.################E00");
} else {
    df = new DecimalFormat("#.###################");
}
String strSaida = df.format(valorSaida).replace('.', ',');

The MAX_DIGITOS constant is 20 and the scale of the BigDecimal variable valorSaida is also 20.

But with numbers such as 0.0000012345, the precision is aways 5, for example, so I can never get the real number of digits in decimal part of the number and therefore I can't format it in scientific notation.

The value is ever cut until reaches 0.00000000000000000001.

Can any one help me?

The scale() method is not useful in this case, because it aways returns the scale 20 as predefined in the BigDecimal variable.

I am looking for a solution without manipulation of digits as in a string.

I tried the code above, but it did not work.

Thanks.


Solution

  • You need to use stripTrailingZeros and scale together, like this.

    BigDecimal valorSaida = new BigDecimal("0.0000012345").setScale(20);
    System.out.println("Scale before stripping: " + valorSaida.scale());
    System.out.println("Scale before stripping: " + valorSaida.stripTrailingZeros().scale());
    

    which prints this.

    Scale before stripping: 20
    Scale before stripping: 10
    

    The scale of the value returned from stripTrailingZeros() will be the number of decimal places that you need, to show all the significant digits.

    Obviously that's different from what precision() returns, because it includes the zeros between the decimal point and the significant digits.