Cannot format double in Java

That's what I'm doing:

double x = 7.0; System.out.printf("%.2f", x); 

Eclipse gives me this error "The printf method (String, Object []) in the PrintStream type is not applicable for arguments (String, double)"

+4
source share
2 answers

Are you using a version of Java older than 1.5? Or maybe an older compiler matching option in Eclipse? (e.g. 1.4). In fact, I'm sure this is the reason. I just switched the compliance setting to 1.4 and got the same error as you.

Check the project compiler matching settings:

  • Choose a project
  • Right click and select Properties
  • go to the "Java Compiler"
  • change compiler compliance and make sure you are using a JRE of this version or higher

This will work if you are using Java 1.5 or higher since the printf method was added in 1.5.

+3
source

I ran the following and I did not have this problem. Are you getting an error from checking Eclipse code or from a 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)); } } 
+2
source

Source: https://habr.com/ru/post/1305628/


All Articles