I have this method:
public void Example(BigDecimal value, int scale){
BigDecimal x = new BigDecimal("0.00001");
System.out.println("result: " + (value.multiply(x)).setScale(scale, RoudingMode.HALF_UP).toString());
If, per example, value = 1 and scale = 2, the output is "result: 0.00". I thought it would be 1.00E-5. So, my doubt is: How can I force a BigDecimal to be formated in scientific notation if its scale is bigger than a certain value (it was 2 in my example) ?
Here is a version of DannyMo's answer that sets the scale automatically:
private static String format(BigDecimal x)
{
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits((x.scale() > 0) ? x.precision() : x.scale());
return formatter.format(x);
}
System.out.println(format(new BigDecimal("0.01"))); // 1.0E-2
System.out.println(format(new BigDecimal("0.001"))); // 1.0E-3
System.out.println(format(new BigDecimal("500"))); // 5E2
System.out.println(format(new BigDecimal("500.05"))); // 5.00050E2
You can use a DecimalFormat
with setMinimumFractionDigits(int scale)
:
private static String format(BigDecimal x, int scale) {
NumberFormat formatter = new DecimalFormat("0.0E0");
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(scale);
return formatter.format(x);
}
...
System.out.println(format(new BigDecimal("0.00001"), 2)); // 1.00E-5
System.out.println(format(new BigDecimal("0.00001"), 3)); // 1.000E-5
You could use something like this:
int maxScale = 2;
BigDecimal value = BigDecimal.ONE;
BigDecimal x = new BigDecimal("0.00001");
BigDecimal result = value.multiply(x);
if (result.scale() > maxScale) {
System.out.format("result: %.2E\n", result); // You can change .2 to the value you need
} else {
System.out.println("result: " + result.toPlainString());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With