For your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.
int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);
Answer from Makoto on Stack OverflowFor your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.
int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);
public static void main(String[] args) {
double x = 6.001;
double y = 5.999;
System.out.println(Math.round(x)); //outputs 6
System.out.println(Math.round(y)); //outputs 6
}
Videos
Hello r/javahelp! I'm learning Java on my own and have been doing some exercises a friend gave me of his past classes when I expressed interest in coding. One of the exercises is to make a program where you convert yards into miles only using ints and a set of numbers given (Example: 60000/70000). Here's the current rendition of the code. For some reason I can't get the numbers that should round, to round (Example: 70000 should round to 40, but I still get 39). I've even tried Math.round() but it doesn't seem to work. In the code, I was hoping that adding 0.5 would bump the round up to 40, but it doesn't. It's really perplexing.
What is the return type of the round() method in the snippet?
If this is the Math.round() method, it returns a Long when the input param is Double.
So, you will have to cast the return value:
int a = (int) Math.round(doubleVar);
If you don't like Math.round() you can use this simple approach as well:
int a = (int) (doubleVar + 0.5);