[英]formatting with printf while printing an array object
我想知道您是否可以执行以下操作:
System.out.printf("%10.2f", car[i]);
考虑到我已经重新定义了toString()
方法。
public void toString() {
return this.getPrice + "" + this.getBrandName;
}
否则,如何格式化打印的价格?
由于toString()
返回String
,因此您可以使用%s
( 请参阅此 )而不是%f
( 请参阅此 )格式化打印对象。
您可以将价格作为浮动价格,并打印格式化的数字以及品牌:
class Car {
public String toString() {
return "I'm a car";
}
public double getPrice() {
return 20000.223214;
}
public String getBrandName() {
return "Brand";
}
}
class Main {
public static void main(String[] args) {
Car c = new Car();
System.out.printf("%10.2f %s", c.getPrice(), c.getBrandName());
}
}
产量
20000.22 Brand
(如果更容易,请以美分表示价格。)
使用String.format()代替。
public void toString() {
return String.format("%10.2f", this.getPrice) + "" + this.getBrandName;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.