10

I am trying to find a way to round values to the nearest 0.05. For example:

  • 0.93 rounds to 0.95
  • 0.81 rounds to 0.80
  • 0.65 stays 0.65
  • 0.68 to 0.70
  • 0.67 to 0.65

Is there a simple way to do this in Java?

Rustam Issabekov
  • 3,279
  • 6
  • 24
  • 31
  • possible duplicate of [How to round a number to n decimal places in Java](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – Brian Roach Feb 13 '12 at 05:33
  • 1
    yes, possible. Did you try anything? Is it a homework? – Nishant Feb 13 '12 at 05:33

1 Answers1

30

One option for doing this would be as follows:

  1. Multiply the value by 20.
  2. Use Math.round to round to the nearest integer.
  3. Divide by 20 again.

For example:

double rounded = Math.round(x * 20.0) / 20.0;

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065