2014-09-30 90 views
0

这涉及到我刚才的问题,它可以在这里找到:如何将数字格式设置为特定数量的小数位数和逗号分隔符?

Math equation result loses decimals when displayed

在我的任务,我们要计算等腰梯形的周长。需要将边界格式化为小数点后4位。如果 小数点后的结果全为零,则不要显示零。 (例如:结果是12.000000什么 将显示为12.)另外如果结果大于1000小数前,那么必须显示 逗号。 (例如:结果是1234.56781将显示的是 1,234.5678)。我们被要求使用十进制格式类。这是我的代码:

//Kyle Collins 
/*This program calculates the area and perimeter of an isosceles trapezoid, as well 
as the diagonal of the isosceles trapezoid. 
*/ 

import java.util.Scanner; 
import java.lang.Math; 
import java.text.*; 

public class CSCD210Lab2 
{ 
    public static void main (String [] args) 
    { 
     Scanner mathInput = new Scanner(System.in); 

     //declare variables 

     double topLength, bottomLength, height,perimPt1,perimPt2; 


     //Get user input 
     System.out.print("Please Enter Length of the Top of Isosceles Trapezoid: ") ; 
     topLength = mathInput.nextDouble() ; 
     mathInput.nextLine() ; 

     System.out.print("Please Enter Length of the Bottom of Isosceles Trapezoid: ") ; 
     bottomLength = mathInput.nextDouble() ; 
     mathInput.nextLine() ; 

     System.out.print("Please Enter Height of Isosceles Trapezoid: ") ; 
     height = mathInput.nextDouble() ; 
     mathInput.nextLine() ; 

     perimPt1 = ((bottomLength - topLength)/2); 
     perimPt2 =(Math.sqrt(Math.pow(perimPt1,2) + Math.pow(height,2))); 

     double trapArea = ((topLength + bottomLength)/2*(height)); 
     double trapDiag = (Math.sqrt(topLength*bottomLength + Math.pow(height,2))); 
     double trapPerim = 2*(perimPt2) + (topLength + bottomLength); 

     //Print the results 
     System.out.println(); 
     System.out.println("The Area of the Isosceles Trapezoid is: "+trapArea); 
     System.out.printf("The Diagonal of the isosceles trapezoid is: %-10.3f%n",trapDiag); 
     System.out.printf("The Perimeter of the Isosceles Trapezoid is: "+trapPerim); 
    } 
} 

我该如何格式化打印输出的边界,以便它使用十进制格式类并满足要求?

回答

4

使用和String.format()

String.format("%.2f", (double)value); 

有不同的方法来定义这个请参考你所需要的。 您还可以使用Decimal Format

+0

我新的Java,所以会使用formatdecimal类? – Kjc21793 2014-09-30 19:28:14

+0

我首先给出的答案是在格式方法的Sting api检查中。 – StackFlowed 2014-09-30 19:31:50

2

使用DecimalFormat格式化数字:

DecimalFormat df = new DecimalFormat("#,###.####", new DecimalFormatSymbols(Locale.US)); 
System.out.println(df.format((double)12.000000)); 
System.out.println(df.format((double)1234.56781)); 
System.out.println(df.format((double)123456789.012)); 

这里这种模式只需要4小数点后切,像你的第二个例子建议。如果您不希望new DecimalFormat("", new DecimalFormatSymbols(Locale.US))也可以使用。

(有必要设置的格式符号或当前区域设置的符号将被使用。这些符号可从desight那些不同)

输出将被

12 
1,234.5678 
123,456,789.012 
相关问题