Java 如何将双精度舍入到最接近的整数并将其作为整数返回

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24420633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:06:11  来源:igfitidea点击:

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

java

提问by user3717539

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

假设我有double x. 我会返回最接近的整数x。例如:

  1. if x = 6.001I would return 6
  2. if x = 5.999I would return 6
  1. 如果x = 6.001我回来6
  2. 如果x = 5.999我回来6

I suppose that I should use Math.ceiland Math.floorfunctions. But I don't know how return nearest whole number...

我想我应该使用Math.ceilMath.floor函数。但我不知道如何返回最接近的整数...

回答by Mike Elofson

int a = (int) Math.round(doubleVar);

This will round it and cast it to an int.

这会将它舍入并将其转换为 int。

回答by Kevin Bowersox

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
}

回答by Makoto

For your example, it seems that you want to use Math.rint(). It will return the closest integer value given a double.

对于您的示例,您似乎想使用Math.rint(). 它将返回给定 a 的最接近的整数值double

int valueX = (int) Math.rint(x);
int valueY = (int) Math.rint(y);   

回答by Sebastian H?ffner

The simplest method you get taught in most basic computer science classes is probably to add 0.5(or subtract it, if your double is below 0) and simply cast it to int.

您在大多数基础计算机科学课程中学到的最简单的方法可能是add 0.5(或减去它,如果您的 double 低于 0)并将其简单地转换为int.

// for the simple case
double someDouble = 6.0001;
int someInt = (int) (someDouble + 0.5); 

// negative case
double negativeDouble = -5.6;
int negativeInt = (int) (negativeDouble - 0.5); 

// general case
double unknownDouble = (Math.random() - 0.5) * 10;
int unknownInt = (int) (unknownDouble + (unknownDouble < 0? -0.5 : 0.5));