Search code examples
javabigdecimal

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


Solution

  • 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