public class StackOF01 {
public static void main(String[] args) {
String schoolTown = "Minneapolis";
String schoolState = "Minnesota";
String county01 = "Ramsey";
String county02 = "Hennepin";
long censusYear = 2010;
long censusPopulation = 382599;
String censusBureau = "Census Bureau";
double area = 6.60;
double land = 6.52;
double water = 0.08;
String river = "Mississippi";
String campus = "University of Minnesota-Twin Cities";
int sections = 2;
System.out.println(schoolTown + ", " + schoolState + ":\n" );
System.out.println(schoolTown + " is a city in " + county01 + " and " + county02 + " counties in the U.S. State "
+ "of " + schoolState + ". " + "As of the census of \n" + censusYear + ", " + "there were " + censusPopulation + " people.\n" );
System.out.println("According to the United States " + censusBureau + "," + " the school has a total area of ");
System.out.printf("%.2f",area);
System.out.println(" square miles, of which,\n" + land + " square miles is land and " + water + " square miles is water.\n");
System.out.println(schoolTown + " lies on the banks of the " + river + " River, The South Fork of the " + river + " River ");
System.out.println("runs through the city, dividing the campus of the " + campus + " into " + sections + " sections." );
}
}
如何打印double类型变量的尾随零而不必从print语句中断?我使用System.out.printf("%.2f",area);
使输出显示为6.60而不是6.6
输出如下:
Minneapolis, Minnesota:
Minneapolis is a city in Ramsey and Hennepin counties in the U.S. State of Minnesota. As of the census of
2010, there were 382599 people.
According to the United States Census Bureau, the school has a total area of
6.60 square miles, of which,
6.52 square miles is land and 0.08 square miles is water.
Minneapolis lies on the banks of the Mississippi River, The South Fork of the Mississippi River |
runs through the city, dividing the campus of the University of Minnesota-Twin Cities into 2 sections.
但我希望输出显示为:
Minneapolis, Minnesota: Minneapolis is a city in Ramsey and Hennepin counties in the U.S. State of Minnesota. As of the census of 2010, there were 382599 people. According to the United States Census Bureau, the school has a total area of 6.60 square miles, of which, 6.52 square miles is land and 0.08 square miles is water. Minneapolis lies on the banks of the Mississippi River, The South Fork of the Mississippi River runs through the city, dividing the campus of the University of Minnesota-Twin Cities into 2 sections.
答案 0 :(得分:1)
您可以使用String.format()
方法。
System.out.println("According to the United States " + censusBureau
+ "," + " the school has a total area of "
+ String.format("%.2f", area) + " square miles, of which,\n"
+ land + " square miles is land and " + water
+ " square miles is water.\n");
答案 1 :(得分:0)
像这样使用 -
System.out.print( String.format( "%.2f", area));