1

I've been assigned to output a double:

myD=1.0/3.0; //using println as  0.33333334 = 1/3. 

I have tried to use a little bit of formatting with no success.

//0.33333334 = 1/3; //only using println 

double myD = 1.0/3.0
System.out.println("%0.8f", myD);

0.33333334

Draken
  • 3,134
  • 13
  • 34
  • 54
Benjamin
  • 13
  • 4

1 Answers1

0

Use DecimalFormat and set rounding mode to always round to the CEILING.

double myD = 1.0/3.0;

DecimalFormat df = new DecimalFormat("#.########");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println(df.format(myD)); 

Output:

0.33333334

If you did not need to round up you could have just used String.format instead to get 0.33333:

System.out.println(String.format("%.8f", myD));  

Output:

0.33333333

Of course that could just be System.out.format("%.8f", myD); as well, but the requirements stated to use System.out.println.

Nexevis
  • 4,647
  • 3
  • 13
  • 22