Cannot output formatted double in Java
Here's what I do:
double x = 7.0;开发者_如何学JAVA
System.out.printf("%.2f", x);
Eclipse gives me this error "The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, double)"
Are you using a version of Java older than 1.5? Or maybe an older compiler compliance setting in Eclipse? (e.g. 1.4) In fact, I am pretty sure that is the cause - I just switched my compliance setting to 1.4 and I get the same error as you.
Check your Project's Compiler Compliance setting:
- Select the Project
- Right click and choose Properties
- go to 'Java Compiler'
- change your compiler compliance and ensure you are using a JRE of that version or higher
This will work once you are using Java 1.5 or higher, since the printf method was added in 1.5.
I ran the following and I didn't seem to have this problem. Are you getting an error from Eclipse's code inspection, or from the Java compiler?
public class TestDouble {
public static void main(String[] args) {
double x = 7.0;
System.out.printf("%.2f", x);
}
}
This will also work and may stop Eclipse from complaining:
public class TestDouble {
public static void main(String[] args) {
double x = 7.0;
System.out.printf("%.2f", new Double(x));
}
}
精彩评论