2011-11-15 21 views
2

我正在处理一个由我的朋友给我的问题。我需要以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()); 
     } 
    } 
} 
+0

我建议先看[DecimalFormat](http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html);它应该能够相对容易地完成大部分你所需要的工作。 – Mike

回答

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

然后成数字,使用:

Float answer = Float.parseFloat(output) 

编辑

还要检查this出来,其中包括如何格式化数字

+0

,但如果我这样做,那么它不会将其转换为科学形式..我怎么能这样做,因此它都有? –

+0

ohh没关系!我知道了。谢谢! –

+0

欢迎:) – PTBG

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^"); 
0

让你的格式字符串” .000" ,它不会从你格式化落‘空’零的更多信息数。