У меня есть двойное число, например 223.45654543434
, и мне нужно показать его как 0.223x10e+2
.
Как я могу сделать это на Java?
У меня есть двойное число, например 223.45654543434
, и мне нужно показать его как 0.223x10e+2
.
Как я могу сделать это на Java?
System.out.println(String.format("%6.3e",223.45654543434));
приводит к
2.235e+02
что мне ближе всего.
дополнительная информация: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
From Отображать числа в научных обозначение. (Копирование/вставка, поскольку на странице возникли проблемы)
Вы можете отображать числа в экспоненциальном представлении, используя пакет java.text
. В частности, для этой цели можно использовать класс DecimalFormat
в пакете java.text
.
В следующем примере показано, как это сделать:
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
}
}
Этот ответ сэкономит время более чем 40 000 человек, которые ищут в Google «научную нотацию Java».
Что означает Y в %X.YE
?
Число между .
и E
– это количество десятичных знаков (НЕ значащих цифр).
System.out.println(String.format("%.3E",223.45654543434));
// "2.235E+02"
// rounded to 3 decimal places, 4 total significant figures
Метод String.format
требует, чтобы вы указали количество десятичных цифр для округления. Если вам нужно сохранить точное значение исходного числа, вам понадобится другое решение.
Что означает X в %X.YE
?
Число между %
и .
– это минимальное количество символов, которое может занимать строка. (это число не обязательно, как показано выше, строка автоматически заполнится, если вы его не укажете)
System.out.println(String.format("%3.3E",223.45654543434));
// "2.235E+02" <---- 9 total characters
System.out.println(String.format("%9.3E",223.45654543434));
// "2.235E+02" <---- 9 total characters
System.out.println(String.format("%12.3E",223.45654543434));
// " 2.235E+02" <---- 12 total characters, 3 spaces
System.out.println(String.format("%12.8E",223.45654543434));
// "2.23456545E+02" <---- 14 total characters
System.out.println(String.format("%16.8E",223.45654543434));
// " 2.23456545E+02" <---- 16 total characters, 2 spaces
Наконец, я делаю это вручную:
public static String parseToCientificNotation(double value) {
int cont = 0;
java.text.DecimalFormat DECIMAL_FORMATER = new java.text.DecimalFormat("0.##");
while (((int) value) != 0) {
value /= 10;
cont++;
}
return DECIMAL_FORMATER.format(value).replace(",", ".") + " x10^ -" + cont;
}
3
легче заметить, чем-
. - person kennytm   schedule 31.05.2010