Java - If 语句需要将值显示为 0.00 而不是 0.0
Java - If statement required to display the value as 0.00 instead of 0.0
我创建此代码以显示特定输出,但输出显示如下:
First Class Parcel - Cost is £3.3
John Smith, 1 Downing Street, SQ13 9DD
Weight = 1.342kg.
这段代码是关于(First Class Parcel - Cost is £3.3) 的输出部分,但是我不想显示 3.3,而是想显示 3.30。
@Override
public String toString() {
String str = "";
double cost = 0.00;
if (this.isFirstClass()){
cost = 3.30;
str = "First Class Parcel";
} else {
cost = 2.80;
str = "Second Class Parcel";
}
return str + " - Cost is £" + cost + "\n" + super.toString() + "\n";
}
你试过了吗:
String.format( "%.2f", cost);
这对你有帮助:
DecimalFormat df = new DecimalFormat("#.00");
double d= 23.2;
System.out.println(df.format(d));
使用DecimalFormat
。像下面这样的东西
double cost = 3.30;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Cost is £" + df.format(cost) );
我创建此代码以显示特定输出,但输出显示如下:
First Class Parcel - Cost is £3.3
John Smith, 1 Downing Street, SQ13 9DD
Weight = 1.342kg.
这段代码是关于(First Class Parcel - Cost is £3.3) 的输出部分,但是我不想显示 3.3,而是想显示 3.30。
@Override
public String toString() {
String str = "";
double cost = 0.00;
if (this.isFirstClass()){
cost = 3.30;
str = "First Class Parcel";
} else {
cost = 2.80;
str = "Second Class Parcel";
}
return str + " - Cost is £" + cost + "\n" + super.toString() + "\n";
}
你试过了吗:
String.format( "%.2f", cost);
这对你有帮助:
DecimalFormat df = new DecimalFormat("#.00");
double d= 23.2;
System.out.println(df.format(d));
使用DecimalFormat
。像下面这样的东西
double cost = 3.30;
DecimalFormat df = new DecimalFormat("#.00");
System.out.println("Cost is £" + df.format(cost) );