Printing the double number of System.out.printf in Java

I have a double number, and I want to print only an integral part of this number. I tried to print it using System.out.printf, but I got it IllegalFormatConversionException. I tried something like:

A()
{ 
    double x;
    //calculate double
    System.out.println("%d",x);
}

I know that I can just print it with System.out.print, but will also print the decimal part. How to do this using printf?

+3
source share
3 answers
System.out.printf("%.0f",x);
  • .0 indicates accuracy. The number is rounded in accordance with the accuracy indicated here. (for example, if you want 2 decimal places to indicate 0.2)
  • f indicates it floating point including doubles (d for decimal integer)
+13
source

%g round-off double integer:

System.out.printf("x=%g%n", x);
0

You can use the following code:

 public static void main(String[] args) {
    double x = 0 ;//The local variable x must be initialized
    System.out.printf("%d",(int)x);//in JDK 5
           //OR
    System.out.printf("%.0f",x);//in JDK 5
           //OR
    System.out.println((int)x);

}
0
source

All Articles