我正在处理一个由我的朋友给我的问题。我需要以x.yzw*10^p
的形式输入输入号码,其中p
非零并且x.yzw
可以是零。我已经制作了该程序,但问题是,当我们有像0.098
这样的数字时,十进制格式将使其成为9.8
,但我需要将其设置为9.800
,它必须始终输出为x.yzw*10^p
。有人可以告诉我这是怎么可能的。Scientifc Notation Java
input: output:
1234.56 1.235 x 10^3
1.2 1.200
0.098 9.800 x 10^-2
代码:
import java.util.Scanner;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class ConvertScientificNotation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("0.###E0");
double input = sc.nextDouble();
StringBuffer sBuffer = new StringBuffer(Double.toString(input));
sBuffer.append("00");
System.out.println(sBuffer.toString());
StringBuffer sb = new StringBuffer(df.format(Double.parseDouble(sBuffer.toString())));
if (sb.charAt(sb.length()-1) == '0') {
System.out.println(sBuffer.toString());
} else {
sb.replace(sb.indexOf("E"), sb.indexOf("E")+1, "10^");
sb.insert(sb.indexOf("10"), " x ");
System.out.println(sb.toString());
}
}
}
我建议先看[DecimalFormat](http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html);它应该能够相对容易地完成大部分你所需要的工作。 – Mike