这与我之前的问题有关,可以在以下网址找到:
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 );
}
}
我如何格式化周边的打印输出,以便它使用小数格式类并满足要求?
答案 0 :(得分:4)
答案 1 :(得分:3)
使用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))
也可以。
(必须设置格式符号或使用当前语言环境的符号。这些符号可能与正确的符号不同)
输出
12
1,234.5678
123,456,789.012