Bryan James
Bryan James

Reputation: 75

Truncating double numbers

I'm working with a java program that computes for the Earliest Deadline Algorithm. Everything seems to work fine except for the double numbers. When I compute for the Averages (Turnaround time and Waiting time), normally the answer would be something like this:

18.566666666666663

I want to CUT (not round off) the answer to two decimal places so the answer should be:

18.56

Okay, so I tried printing the results on the console screen:

System.out.println (String.format ("%.2f", ttAve)); // ttAve contains 18.566666666666663

But then, the numbers will be rounded off when printed:

18.57

What should I do?

Upvotes: 0

Views: 594

Answers (4)

Ramachandra Reddy
Ramachandra Reddy

Reputation: 301

Can you try with the below code?

DecimalFormat format = new DecimalFormat("#.##");
format.setRoundingMode(RoundingMode.FLOOR);
System.out.println (format.format(ttAve));

Upvotes: 0

Arsenicum
Arsenicum

Reputation: 101

You can use this method:

float roundResult (float f) {
   int precise = 100;
   f = f * precise;
   int i = (int) f;
   return (float) i / precise;
}

Upvotes: 0

Saravanakumar Vadivel
Saravanakumar Vadivel

Reputation: 96

You can do something like

double cutValue = Math.floor(a * 100.0) / 100.0;

Upvotes: 0

Tagir Valeev
Tagir Valeev

Reputation: 100209

Use DecimalFormat:

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

Note that both System.out.printf and DecimalFormat use system-default locale for formatting, so you may see unexpectedly 18,56 instead of 18.56 in some countries. If this is undesired, you can specify the locale explicitly:

DecimalFormat df = new DecimalFormat("#.##", 
                                     DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setRoundingMode(RoundingMode.DOWN);
System.out.println(df.format(18.566666666666663));

Upvotes: 2

Related Questions