Java - 只显示两个小数点?

时间:2015-11-20 10:08:27

标签: java arrays decimalformat

所以我的程序也会完成我想要的所有内容,除了在随机数为temps生成时只显示小数点后的2个位置(12.00)。现在正在做的是(12.1234567897654)。

我是java的初学者,这是我自己完成的第一个程序,所以如果答案显而易见,请不要吝啬D:

我尝试过printf和%。2f,但我无法让它工作

public class ArrayOfTemperatures
{
  public static void main(String[] args)
   {

  double [] temp = new double [7];


  double random = Math.random() * 100 + 1;

  temp[0] = Math.random() * 100 + 1;

     //Calculating average          
     int sum = 0;
     for (int i = 0; i < temp.length; i++) {
        temp[i] =  Math.random() * 100 + 1;
        sum += temp[i];
      }

     //average being stated
     double average = (double) sum / temp.length;
     System.out.println("The average temperature is " + average);

    //Temperatures
    for (int i = 0; i < temp.length; i++) {
     temp[i] =  Math.random() * 100 + 1;
     System.out.print("Temperature " + (i + 1) + " is: " + temp[i]);
        if (temp[i] > average){
           System.out.println(" and is above average.");
        }
        else {
           System.out.println(" and is below average.");
        }


      }          

   }         
}

输出的一个例子是:

The average temperature is 42.714285714285715
Temperature 1 is: 14.71803486458223 and is below average.
Temperature 2 is: 33.10321474550992 and is below average. 
Temperature 3 is: 18.661262675746727 and is below average. 
Temperature 4 is: 82.12893152205741 and is above average. 
Temperature 5 is: 90.97086140892438 and is above average. 
Temperature 6 is: 19.609064446916477 and is below average. 
Temperature 7 is: 75.47742502105827 and is above average. 

5 个答案:

答案 0 :(得分:5)

如果您想将其用于显示目的,请使用java.text.DecimalFormat

new DecimalFormat("#.##").format(dblVar);

如果您需要它进行计算,那么:

Math.floor(value * 100) / 100

SourceBozho

的原始答案

答案 1 :(得分:1)

您可以使用格式化功能。基本上,它与printf一样。尝试

System.out.println(String.format("Temperature %d is: %.2f", i + 1, temp[i]));

答案 2 :(得分:1)

Use this 
System.out.printf("%.2f", temp);

答案 3 :(得分:1)

只需使用printf:

 System.out.printf ("The average temperature is %.2f", average);

System.out.printf("Temperature %d is: %0.2f ", (i + 1), temp[i]);

答案 4 :(得分:0)

可以使用String.format()方法

来解决
System.out.println("The average temperature is " + average);

按以下代码替换此行:

System.out.println("The average temperature is " + String.format("%.02f", average));

System.out.print("Temperature " + (i + 1) + " is: " + temp[i]);

按以下代码替换此行:

System.out.println("Temperature " + (i + 1) + " is: " + String.format("%.02f", temp[i]));