Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Efficient method to round double on 0.05

hsc71May 27 2015 — edited May 28 2015

I've a question on rounding doubles on 0.05

As far as i know there is no class method that is able to do this. To achieve this rounding i have the following code:

Example:

164.67 -> 164.70

173.33 -> 173.35

0.02 -> 0.05

double calculatedQuantity = 0.0;

  // Formula to calculate the average working hours in a month

  int totalWeeksInYear = 52;

  int totalMonthsInYear = 12;

  calculatedQuantity = (quantity * totalWeeksInYear) / totalMonthsInYear;

// Round the 2 decimals

  calculatedQuantity = calculatedQuantity * 100;

  calculatedQuantity = Math.round(calculatedQuantity);

  //The rounding has to be on 0.05 in the benefit of the employee. Use modulus to get a 0 or 5

  while(calculatedQuantity%5!=0){

  calculatedQuantity = calculatedQuantity + 1;

  }

  calculatedQuantity = calculatedQuantity/100;

  calculatedQuantity = calculatedQuantity/100;

This works but i don't have the feeling this is efficient.

Any suggestions would be very welcome.

Regards,

Hans

This post has been answered by RajenB on May 27 2015
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 25 2015
Added on May 27 2015
4 comments
968 views