Display numbers in scientific notationTag(s): String/Number


JDK1.0.2
public static String toScientific(double num,int places) {
  String result="";
  String sign="";

  double power=(int)(Math.log(num)/Math.log(10));
  if(power < 0) power--;
  double fraction=num/Math.pow(10,power);
  fraction=round(fraction,places);
  if(power > 0) sign="+";
  result += fraction + "e" + sign + power;
  return result;
}

public static double round(double value, int decimalPlace) {
  double power_of_ten = 1;
  while (decimalPlace-- > 0) power_of_ten *= 10.0;
  return Math.round(value * power_of_ten) / power_of_ten;
}

JDK1.2+
A much better way is now in the java.text package :
import java.text.*;
import java.math.*;

public class TestScientific {

  public static void main(String args[]) {
     new TestScientific().doit();
  }

  public void doit() {
     NumberFormat formatter = new DecimalFormat();

     int maxinteger = Integer.MAX_VALUE;
     System.out.println(maxinteger);    // 2147483647

     formatter = new DecimalFormat("0.######E0");
     System.out.println(formatter.format(maxinteger)); // 2,147484E9

     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(maxinteger)); // 2.14748E9


     int mininteger = Integer.MIN_VALUE;
     System.out.println(mininteger);    // -2147483648

     formatter = new DecimalFormat("0.######E0");
     System.out.println(formatter.format(mininteger)); // -2.147484E9

     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(mininteger)); // -2.14748E9

     double d = 0.12345;
     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(d)); // 1.2345E-1

     formatter = new DecimalFormat("000000E0");
     System.out.println(formatter.format(d)); // 12345E-6
  }
}

blog comments powered by Disqus