Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round double to nearest whole number and return it as Integer

Tags:

java

Let suppose that I have double x. I would return nearest whole number of x. For example:

  1. if x = 6.001 I would return 6
  2. if x = 5.999 I would return 6

I suppose that I should use Math.ceil and Math.floor functions. But I don't know how return nearest whole number...

like image 717
user3717539 Avatar asked Jun 26 '14 00:06

user3717539


2 Answers

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);   
like image 90
Makoto Avatar answered Sep 30 '22 12:09

Makoto


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
}
like image 29
Kevin Bowersox Avatar answered Sep 30 '22 14:09

Kevin Bowersox