Java 将双精度转换为整数,向下舍入
如何将Java 将双精度转换为整数,向下舍入,java,type-conversion,rounding,Java,Type Conversion,Rounding,如何将double值转换为int执行以下操作: Double If x = 4.97542. Convert to int x = 4. Double If x = 4.23544. Convert to int x = 4. 也就是说,答案总是四舍五入。如果显式地将double转换为int,小数部分将被截断。例如: int x = (int) 4.97542; //gives 4 only int x = (int) 4.23544; //gives 4 only 此外,您还可以
double
值转换为int
执行以下操作:
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
也就是说,答案总是四舍五入。如果显式地将
double
转换为int
,小数部分将被截断。例如:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
此外,您还可以使用Math.floor()
方法对值进行四舍五入,以防需要double
值作为回报
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
如果double是一个大写字母D的
double
(一个装箱的原始值),则double值为420.5,应用程序将打印出整数值420:
如果double已经是一个原语double
,则只需将其强制转换为:
double d = 4.97542;
int i = (int) d;
我认为我有更好的输出,特别是对于双数据类型排序 虽然这个问题已经被标记为答案,也许这会帮助其他人
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);
}
});
Arrays.sort(newTag,newcomparator(){
@凌驾
公共整数比较(最终字符串[]entry1,最终字符串[]entry2){
final Integer time1=(int)Integer.valueOf((int)Double.parseDouble(entry1[2]);
最终整数time2=(int)Integer.valueOf((int)Double.parseDouble(entry2[2]);
返回时间1.比较(时间2);
}
});
使用Double
或Double
的另一个选项是使用Double.valueOf(Double d).intValue()代码>。简单明了你能告诉我Double和Double的区别吗?Double是一个基本的浮点值。Double是Java对象,“松散的十进制值”是什么意思?它给出的数字是否与调用Math.floor()
时给出的数字相同?Double不是整数,因此转换不起作用。注意Double类和Double原语之间的区别。还请注意,Double是一个数字,因此它具有方法intValue,您可以使用该方法将值转换为原始int。如果尝试将Double转换为int,您将得到转换异常:java.lang.ClassCastException:java.lang.Double不能转换为java.lang.Integer
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);
}
});