简体   繁体   English

将double转换为Int,四舍五入

[英]Convert double to Int, rounded down

How to convert a double value to int doing the following: 如何执行以下操作将double值转换为int

Double If x = 4.97542. Convert to int x = 4.

Double If x = 4.23544. Convert to int x = 4.

That is, the answer is always rounding down. 也就是说,答案总是四舍五入。

If you explicitly cast double to int , the decimal part will be truncated. 如果 double显式转换为int ,则小数部分将被截断。 For example: 例如:

int x = (int) 4.97542;   //gives 4 only
int x = (int) 4.23544;   //gives 4 only

Moreover, you may also use Math.floor() method to round values in case you want double value in return. 此外,如果您想返回double Math.floor()值,也可以使用Math.floor()方法对值进行舍入。

If the double is a Double with capital D (a boxed primitive value): 如果double是具有大写DDouble (装箱的原始值):

Double d = 4.97542;
int i = (int) d.doubleValue();

// or directly:
int i2 = d.intValue();

If the double is already a primitive double , then you simply cast it: 如果double已经是原始double ,则只需将其强制转换为:

double d = 4.97542;
int i = (int) d;
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420 双精度值是420.5,应用程序将打印出整数值420

Another option either using Double or double is use Double.valueOf(double d).intValue(); 使用Doubledouble另一个选项是使用Double.valueOf(double d).intValue(); . Simple and clean 简单干净

I think I had a better output, especially for a double datatype sorting. 我认为我有更好的输出,尤其是对于双重数据类型排序。

Though this question has been marked answered, perhaps this will help someone else; 尽管此问题已被标记为已回答,但也许这会对其他人有所帮助。

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM