Dan*_*ico 25 java formatting scientific-notation
我有一个双号223.45654543434,我需要表现出来0.223x10e+2.
我怎么能用Java做到这一点?
Pet*_*ans 29
System.out.println(String.format("%6.3e",223.45654543434));
Run Code Online (Sandbox Code Playgroud)
结果是
2.235e+02
Run Code Online (Sandbox Code Playgroud)
这是我最接近的.
更多信息:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax
Gre*_*ead 22
来自科学记数法中的显示数字.(复制/粘贴因为页面似乎有问题)
您可以使用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
}
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*e S 18
这个答案将为4万多人用Google搜索"java科学记法"节省时间.
你的意思是%X.YE什么?
.和之间的E数字是小数位数(不是有效数字).
System.out.println(String.format("%.3E",223.45654543434));
// "2.235E+02"
// rounded to 3 decimal places, 4 total significant figures
Run Code Online (Sandbox Code Playgroud)
该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
Run Code Online (Sandbox Code Playgroud)
Dan*_*ico -10
最后我手工完成:
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;
}
Run Code Online (Sandbox Code Playgroud)