如何在java中将5.5转换为5.0

如何在java中将5.5转换为5.0,java,Java,我知道这听起来很愚蠢。但我不知道如何将5.5转换成5.0 我所做的是: int expiry = month2 + month1; int expiry1 = expiry; int sum = 0; DecimalFormat df = new DecimalFormat("#.00000"); df.format(expiry); if (expiry > 12) { expiry = (expiry / 12); sum = ((expiry1 - (expiry

我知道这听起来很愚蠢。但我不知道如何将5.5转换成5.0

我所做的是:

int expiry = month2 + month1;
int expiry1 = expiry;
int sum = 0;

DecimalFormat df = new DecimalFormat("#.00000");
df.format(expiry);
if (expiry > 12) {
    expiry = (expiry / 12);

    sum = ((expiry1 - (expiry * 12)) - 1);
    System.out.println(sum);
    month3 = sum;
    year1 = (year1 + expiry);

}

如果考虑到期值时的条件是例如30,则由于小数而使输出为3,但我希望答案为2。我尝试使用十进制格式,但不起作用。我试过铸造,但在尝试时失败了(也许我不知道正确的方法)

我试着使用这个模式

String truncatedValue = String.format("%d", expiry).split("\\.")[0];

然后再次将其转换为整数,但这对我不起作用。

正如评论中指出的,您可以使用
Math.floor
。 另一个选项是转换为
long
或使用
Math.round
。下面是获取
x=5
的选项概述:

// Casting: Discards any decimal places
double a = (long) 5.4;
System.out.println(a); // 5.0

double b = (long) 5.6;
System.out.println(b); // 5.0

double c = (long) -5.4;
System.out.println(c); // -5.0

double d = (long) -5.6;
System.out.println(d); // -5.0

// Math.floor: Rounds towards negative infinity
double e = Math.floor(5.4);
System.out.println(e); // 5.0

double f = Math.floor(5.6);
System.out.println(f); // 5.0

double g = Math.floor(-5.4);
System.out.println(g); // -6.0

double h = Math.floor(-5.6);
System.out.println(h); // -6.0

// Math.round: Rounds towards the closest long
double i = Math.round(5.4);
System.out.println(i); // 5.0

double j = Math.round(5.6);
System.out.println(j); // 6.0

double k = Math.round(-5.4);
System.out.println(k); // -5.0

double l = Math.round(-5.6);
System.out.println(l); // -6.0
如果你只是想去掉小数点,铸造是很好的

如果要舍入到下一个较小的值,
Math.floor
是您的朋友

如果你想让我们大多数人在学校里学习数学的方法变得更全面,
Math.round


为了便于将来参考,您可以假设基本的数学运算(如向上/向下取整)在各自的库中实现,因此快速搜索主题不会有什么坏处。

为什么不使用?或
双d=5.5;d=(双精度)(整数)d,丑得要命,但是works@sss,不正确
Math.floor()
将始终返回小于传递的数字的最近整数。因此,直到
5.9
,它将只返回
5
。@sss I将javadoc链接到该方法。你读过吗?@sss进入我的第一条评论,点击
Math.floor(double)