I would like to print a BigDecimal
in scientific notation so that the there are, say, 5 digits after the decimal point. For example: -3.12345E-51
, 9.12345E100
.setScale()
does not work in this case, because I don't know in advance the exponent of number in scientific notation. Moreover, BigDecimal
doesn't seem to have a getExponent()
method.
What's the best way to achieve this? Thank you in advance.
You should use DecimalFormat to print numbers in specified format:
BigDecimal bigDecimal = new BigDecimal(-3.12345E-51);
DecimalFormat format = new DecimalFormat("0.#####E0");
System.out.println(format.format(bigDecimal));
Also you can configure count of fraction digits using method DecimalFormat#setMaximumFractionDigits(int):
DecimalFormat format = new DecimalFormat("0E0");
format.setMaximumFractionDigits(6);