Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print double number System.out.printf in Java

Tags:

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?

like image 735
Rog Matthews Avatar asked Dec 07 '22 14:12

Rog Matthews


1 Answers

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)
like image 198
Kilian Foth Avatar answered Dec 21 '22 17:12

Kilian Foth