Please help me to set output of BigDecimal. For example: I need to output numbers which have a length that is less than 8 digits like this: "12345678", and if more then: "1,2345Е+9".
Methods
toPlainString();
toEngineeringString();
toString();
are not working as expected:
public class TestBigDecimalOutput {
public static void main(String[] args) {
BigDecimal d = new BigDecimal("57657657657453646587980887663654676580.24545346565476767645");
String outPlainString = d.toPlainString();
String outEngineeringString = d.toEngineeringString();
String outString = d.toString();
System.out.println(outPlainString);
System.out.println(outEngineeringString);
System.out.println(outString);
}
}
The code above produces the following output:
57657657657453646587980887663654676580.24545346565476767645
57657657657453646587980887663654676580.24545346565476767645
57657657657453646587980887663654676580.24545346565476767645
Give me a hint what am I doing wrong?
To the best of my knowledge (and I kind of hope I'm wrong) you can't make a BigDecimal render in a particular way. There's no way (that I know) to make it use scientific or engineering notation, or to control when it does. Engineering notation will only used with the number "needs an exponent," and the circumstances in which it will need an exponent are explained in the documentation for BigInteger.toString(). I find the explanation hard to follow, frankly, and I've never been able to figure out how to make the behaviour follow a useful pattern in an application.
I've found that it's easier just not to try, and to format the number myself. That means extracting the mantissa and exponent in base 10, and then concatenating as strings with an "E" between the components. The mantissa part will need to be rounded, probably. If you know the exponent (in base 10) you can work out from its magnitude whether it exceeds the threshold you want, for using scientific notation. If it doesn't, you can just use BigDecimal.toPlainString(), perhaps with suitable rounding.
Engineering notation can be handled in the same way, but with the exponent rounded to the nearest multiple of three, and the mantissa adjusted to compensate.
There's a useful library 1 that can do the necessary logarithm and power operations, or see this question 2 for some suggestions.
I have some code that does this stuff, which I'm quite happy to share, but it's way to long to include, and I can't promise that it's production-quality, or even readable.