-1

I keep getting crazy decimals. For example, two of the numbers my code returned were 73.897886248014 and 46.102113751985996.

I simply need a method that returns 74.0 and 46.0. The data type needs to stay as a Double. I've tried several things, but I can't do it without changing the data type.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
ayojava
  • 1
  • 2

1 Answers1

4

Java has a function just for this: Math.rint. It takes a double and rounds it to the nearest integer, but it returns a double instead of an int like Math.round does.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • 1
    It is better to link to the official documentation, e.g. https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#rint-double- – Andreas Nov 12 '20 at 01:44
  • I had no idea that this was a method or that there was a common-enough need for it that it was part of the standard API. Interesting, thank you. This is a better solution than the one in the answer linked in the duplicate (for this specific case of 0 decimal places, mind). – BeUndead Nov 12 '20 at 01:54