我在打印格式上有个小问题。如果小数点不是整数(例如,55.53467 -> 55.53),则在小数点之后打印2位数字(例如,55.53467 -> 55.53),如果小数点是整数或小数点后面有圆号(例如,2.00 -> 2.0或5.10 -> 5.1),则打印小数点后的1位数字。
我的代码是:
public String toString() {
return String.format("%+.2f%+.2fX%+.2fX^2%+.2fX^3%+.2fx^4", this.A0.getCoefficient()
, this.A1.getCoefficient()
, this.A2.getCoefficient()
, this.A3.getCoefficient()
, this.A4.getCoefficient());
}当然,它总是打印两位数字。非常感谢
发布于 2016-03-16 20:33:49
您可能希望利用DecimalFormat,例如:
public static String format(double num, double places) {
String format = "#.";
for(int i=0; i<places; i++) format += "0";
DecimalFormat df = new DecimalFormat(format);
return df.format((int)(num * Math.pow(10, places)) / (double) Math.pow(10, places));
}然后,您可以使用它到任何小数位:
System.out.println(format(1, 2)); // 1.00
System.out.println(format(234, 2)); // 234.00
System.out.println(format(-55.12345, 2)); // -55.12
System.out.println(format(7.2, 2)); // 7.20发布于 2016-03-16 20:30:21
在本例中,我将使用DecimalFormat "0.0#“(#:如果不是设置为零)格式化浮点数,将结果传递给函数String.format。
https://stackoverflow.com/questions/36046176
复制相似问题