Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing BigDecimals to use scientific notation

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) ?

like image 670
Luso Avatar asked Aug 02 '13 22:08

Luso


3 Answers

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
like image 158
Steve Waring Avatar answered Oct 30 '22 23:10

Steve Waring


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
like image 28
DannyMo Avatar answered Oct 30 '22 23:10

DannyMo


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());
}
like image 35
AleX Avatar answered Oct 30 '22 22:10

AleX