-4

I am currently figuring out how to round amounts like 8.3 to 8.5 or 8.6 to 9.0 with the Math.round method.

My current way to go is checking, if the initial value is smaller than the rounded value and then +.5 or -.5.

like this:

if(amountB < Math.round(amountB))
        {
            System.out.println(Math.round(amountB ) - .5);
        }

But thats not working how I want it to, it always puts out 8.5, even when the input is 8.6.

Thanks for any advice.

  • `8.6` is closer to `8.5` than it is to `9.0` isn't it? Don't you mean you wan to "ceil" it? What should the output for `8.1` be? – Ivar Oct 19 '18 at 10:30
  • 2
    Possible duplicate of: https://stackoverflow.com/questions/23449662/java-round-to-nearest-5 , the answer https://stackoverflow.com/a/23449769/4417306 should solve your question. – Mark Oct 19 '18 at 10:31
  • 3
    Possible duplicate of [Best method to round up to the nearest 0.05 in java](https://stackoverflow.com/questions/11815135/best-method-to-round-up-to-the-nearest-0-05-in-java) – T A Oct 19 '18 at 10:32
  • @Mark "_or 8.6 to 9.0_". That answer will output 8.5. – Ivar Oct 19 '18 at 10:35
  • 8.6 rounded to 9.0 subtract 0.5 is 8.5. – Peter Lawrey Oct 19 '18 at 11:24
  • Can you give more examples of what you want unless one of the answers can be accepted. – Peter Lawrey Oct 19 '18 at 11:26

2 Answers2

1

I'd do it like this:

public class MyClass {
private static double myRound(double x) {
    return Math.ceil(x*2.0) /2.0;
}

public static void main(String args[]) {
    double x = 8.2;
    double y = 8.6;
    double z = 8.8;

    System.out.println("" + x + " rounded upwards is = " + myRound(x));
    System.out.println("" + y + " rounded upwards is = " + myRound(y));
    System.out.println("" + z + " rounded upwards is = " + myRound(z));
}

//8.2 rounded is = 8.5
//8.6 rounded is = 9.0
//8.8 rounded is = 9.0
}
Adder
  • 5,708
  • 1
  • 28
  • 56
  • "_or 8.6 to 9.0_". This answer will output 8.5. – Ivar Oct 19 '18 at 10:37
  • Yes I believe that is a bug in the specification in the question. – Adder Oct 19 '18 at 10:38
  • 1
    The question _is_ the specification. OP explicitly says "_But thats not working how I want it to, it always puts out 8.5, even when the input is 8.6._" – Ivar Oct 19 '18 at 10:39
  • You can use `Math.ceil(x*2.0) /2.0;` instead of `Math.round(x*2.0) /2.0;` if you want to round upwards. Maybe the question could be clarified. – Adder Oct 19 '18 at 10:41
  • [Hence my comment](https://stackoverflow.com/questions/52890549/math-roundx-rounding-to-5#comment92693699_52890549). If your answer is actually the answer, it should be closed [as a duplicate](https://stackoverflow.com/questions/23449662/java-round-to-nearest-5). But as long as it is unclear, it [shouldn't be answered](https://stackoverflow.com/help/how-to-answer). – Ivar Oct 19 '18 at 10:44
0

You can try this;

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

2.0 is coming from 1/0.5

kaan bobac
  • 729
  • 4
  • 8