I have a double number like 223.45654543434
and I need to show it like "0.223x10E-3"
.
How can I do this in Java?
I have a double number like 223.45654543434
and I need to show it like "0.223x10E-3"
.
How can I do this in Java?
From http://www.java-tips.org/java-se-tips/java.text/display-numbers-in-scientific-notation.html
Copy/pasting because the page seems to be having issues
=================
You can display numbers in scientific notation using java.text package. Specifically DecimalFormat class in java.text package can be used for this aim.
The following example shows how to do this:
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
}
}
System.out.println(String.format("%6.3e",223.45654543434));
results in
2.235e+02
which is the closest I get.
more info : http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
Finally I do it by hand:
public static String parseToCientificNotation(double valor) {
int cont = 0;
java.text.DecimalFormat DECIMAL_FORMATER = new java.text.DecimalFormat("0.##");
while (((int) valor) != 0) {
valor /= 10;
cont++;
}
return DECIMAL_FORMATER.format(valor).replace(",", ".") + " x10^ -" + cont;
}
thanks to all :)