2017-10-08 27 views
-3

我正在构建温度表,我不确定如何在我的程序的for循环中实现小数格式。我已经添加了十进制格式。下面是我的程序循环部分:如何把我的程序以正确的十进制格式使用十进制格式类?

DecimalFormat pattern = new DecimalFormat("##0.##"); 


String table = " Faren. Celsius Kelvin ";  // Create the header 
table += "\n------------------------";   // Add the heading underline 

for (double i = start; i <= end ; i += step) 

     { 

      double c = ((5.0/9.0) * (i - 32)); 
      double k = c + 273.15; 

    table += "\n | " + i + "\t | " +c + " | \t" + k + " |\n"; 

} 
      table += "\n------------------------"; 
System.out.println (table); 
JOptionPane.showMessageDialog(null, (table)); 
+0

你应该使用'pattern.format(c)'而不是'c'。 另请参阅方法['format(Object)']的javadoc(https://docs.oracle.com/javase/8/docs/api/java/text/Format.html#format-java.lang.Object- )。 –

回答

0

要格式化用DecimalFormat(或一般NumberFormat)一个数字,你可以使用的各种format方法之一。根据你的情况为格式化double你应该使用 public final String format(double number),即对于你的榜样

String cFormatted = pattern.format(c); 
String kFormatted = pattern.format(k); 

然后你可以在字符串连接,而不是ck使用这些字符串。 当然,如果需要,也可以使用相同的方法来格式化i