【发布时间】:2011-11-15 14:21:01
【问题描述】:
我正在解决我朋友给我的一个问题。我需要采用x.yzw*10^p 形式的输入数字,其中p 不为零,x.yzw 可以为零。我已经制作了程序,但问题是当我们有诸如0.098之类的数字时,十进制格式将使其变为9.8,但我需要将其设置为9.800,它必须始终输出为x.yzw*10^p .谁能告诉我这是怎么可能的。
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;它应该可以相对轻松地完成大部分您正在寻找的事情。
标签: java decimal scientific-notation