这涉及到我刚才的问题,它可以在这里找到:如何将数字格式设置为特定数量的小数位数和逗号分隔符?
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);
}
}
我该如何格式化打印输出的边界,以便它使用十进制格式类并满足要求?
我新的Java,所以会使用formatdecimal类? – Kjc21793 2014-09-30 19:28:14
我首先给出的答案是在格式方法的Sting api检查中。 – StackFlowed 2014-09-30 19:31:50