2

我正在解决我朋友给我的一个问题。我需要采用非零且可以为零x.yzw*10^p的形式输入数字。我已经制作了程序,但问题是当我们有数字时,十进制格式会制作它,但我需要让它成为,它必须始终输出为。有人可以告诉我这是怎么可能的。px.yzw0.0989.89.800x.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());
        }
    }
}
4

3 回答 3

2
DecimalFormat myFormatter = new DecimalFormat(".000");
String output = myFormatter.format(input)

那么如果要将“输出”转换为数字,请使用:

Float answer = Float.parseFloat(output)

编辑

也检查一下,它包含有关如何格式化数字的更多信息

于 2011-11-15T14:29:24.827 回答
1
DecimalFormat df = new DecimalFormat("0.###E0");
df.setMinimumFractionDigits(3);
df.setMaximumFractionDigits(3);

String formatted = df.format(0.098); //"9.8E-2"

然后你可以对 E 进行搜索和替换:

String replaced = formatted.replaceAll("E", " x 10^");
于 2011-11-15T14:26:37.077 回答
0

使您的格式字符串为“.000”,它不会从您的格式化数字中删除“空”零。

于 2011-11-15T14:30:59.263 回答