Reputation: 3247
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
Reputation: 14346
System.out.printf("%.0f",x);
Upvotes: 15
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
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