3

I'm trying to find a way on how to round to the nearest 0.05 in java. Let's say that I have the following numbers:

0.33
0.02
0.874
0.876

This should become:

0.35
0.00
0.85
0.90

I tried many things and I can only get it to round to n places behind the comma by using BigDecimal, but I can't seem to find a way for this one.

Can someone help me?

EDIT: Thank you for all your help, I am amazed at how easy this could be done. And how do I get the double converted into a string properly? I can't use Double.toString(double d) because for example the string will be "0.9" instead of "0.90"?

n00b1990
  • 1,189
  • 5
  • 17
  • 25
  • Do you need it rounded and stored as a number, or just displayed as string? I know you can format strings with a specific number of decimal places, but I'm not sure off hand how to do it as a number. – Brian J May 06 '14 at 14:08
  • multiply by 20, round, divide by 20, works out to the same number – Marshall Tigerus May 06 '14 at 14:09
  • And how can the double be properly formatted to a string, like explained above? – n00b1990 May 06 '14 at 14:27

4 Answers4

4

0.05 == 1/20, right? Therefore, what you need is just the nearest number with dividing by 1/20, so, you may multiply this number by 20, get the nearest number with dividing by 1, then get the initial things.

TL;DR: you just may just multiply it by 20, round and divide by 20 again:

public double customRound(double num) {
    return Math.round(num * 20) / 20.0;
}
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
4

A simple way would be:

double d = 0.33;
double roundedTimes20 = Math.round(d * 20);
double rounded = roundedTimes20 / 20; //0.35

but note that the resulting double is not necessarily the exact representation of the rounded number (usual floating point caveat) and that the method assumes that your original double times 20 can fit in a long.

assylias
  • 321,522
  • 82
  • 660
  • 783
1

Try a function:

    public static double round05(double num) {
            return Math.round(num * 20) / 20.0;
    }
user3608167
  • 61
  • 1
  • 4
1

You can use String.format to format value to String

String s = String.format("%.2f", 0.9);
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275