我有一个双数 like 223.45654543434
,我需要显示它 like 0.223x10e+2
。
我怎样才能在 Java 中做到这一点?
我有一个双数 like 223.45654543434
,我需要显示它 like 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
来自以科学计数法显示数字。(复制/粘贴,因为页面似乎有问题)
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
}
}
这个答案将为搜索“java 科学记数法”的 40k+ 人节省时间。
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;
}