Rog Matthews
Rog Matthews

Reputation: 3247

Print double number System.out.printf in Java

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

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

I know that i can simply print it using System.out.print but that will print the decimal part too. How can i do this using printf?

Upvotes: 4

Views: 41026

Answers (3)

Kilian Foth
Kilian Foth

Reputation: 14346

System.out.printf("%.0f",x);
  • The .0 specifies the precision. Number is rounded off according to the precision specified here. (e.g. if you want 2 decimal places you would specify 0.2)
  • The f specifies it's a floating point - including doubles (d is for decimal integer)

Upvotes: 15

Mark Yao
Mark Yao

Reputation: 408

You can use follow 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);

}

Upvotes: 0

anubhava
anubhava

Reputation: 785128

You can also use %g as well to round-off and print double as integer:

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

Upvotes: 0

Related Questions