gpt4 book ai didi

java - 如何在java中将5.5转换为5.0

转载 作者:行者123 更新时间:2023-11-30 03:20:55 25 4
gpt4 key购买 nike

我知道这听起来很愚蠢。但我不知道如何将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 是您的 friend 。

如果您想对我们大多数人在学校学习的方式进行舍入,Math.round 就可以。

为了将来的引用,您可以假设基本的数学运算(例如向上/向下舍入)是在各自的库中实现的,因此快速搜索该主题不会有什么坏处。

关于java - 如何在java中将5.5转换为5.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com