Java - 如何将 float (或 BigDecimal )值向上舍入 0.5?
似乎很简单的问题,但我的数学真的很糟糕,而且我在网上搜索到的一些例子似乎对我不起作用。 (结果只是返回与输入相同的值等)
例如..但它是 C 语言而不是 Java 语言 C 中的舍入到下一个 .05
所以我的目标是我有 %.1f
格式 float
或 double
或 大十进制
并希望将其四舍五入到最接近的 0.5 strong>
example:
1.3 --> 1.5
5.5 --> 5.5
2.4 --> 2.5
3.6 --> 4.0
7.9 --> 8.0
我尝试了以下示例,但没有成功:( 下面仅输出 1.3,这是原始值。我希望它是 1.5
public class tmp {
public static void main(String[] args) {
double foo = 1.3;
double mid = 20 * foo;
System.out.println("mid " + mid);
double out = Math.ceil(mid);
System.out.println("out after ceil " + out);
System.out.printf("%.1f\n", out/20.0);
}
}
Seems simple question but I really suck at math and few examples online I've searched seems not working for me. (the result just return the same value as input etc)
For instance.. but its in C not Java
Round to Next .05 in C
So my goal is I have %.1f
format float
or double
or big decimal
and wanting to round it up to nearest .5
example:
1.3 --> 1.5
5.5 --> 5.5
2.4 --> 2.5
3.6 --> 4.0
7.9 --> 8.0
I tried following example but didn't work :( below just output 1.3 which is original value. I wanted it to be 1.5
public class tmp {
public static void main(String[] args) {
double foo = 1.3;
double mid = 20 * foo;
System.out.println("mid " + mid);
double out = Math.ceil(mid);
System.out.println("out after ceil " + out);
System.out.printf("%.1f\n", out/20.0);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这是一个简单的方法:
将值加倍,取其上限,然后将其减半。
Here's a simple method:
This doubles the value, takes its ceiling, and cuts it back in half.
乘以(然后除以)2,而不是 20,应该可以解决问题。
Multiplying (and later dividing) by 2, not 20, should do the trick.
下面的公式对于 2.16 这样的数字不太适用,
正确答案应该是 2.0,但是上面的方法给出 2.5
正确的代码应该是:
The below formula does not work well for number like 2.16
The correct answer should be 2.0, but the above method gives 2.5
The correct code should be:
请参阅 Big Decimal Javadoc 关于为什么在构造函数中使用 String
See the Big Decimal Javadoc about why a String is used in the constructor
不使用函数,您可以执行
注:这将四舍五入到无穷大。
Without using a function, you can do
Note: this will round towards infinity.
其他一些答案舍入不正确(应该使用
Math.round
,而不是Math.floor
或Math.ceil
),而其他答案只能工作四舍五入到 0.5(这就是问题所问的,是的)。这是一个简单的方法,可以正确舍入到最接近的任意双精度数,并进行检查以确保它是正数。Some of the other answers round incorrectly (
Math.round
should be used, notMath.floor
orMath.ceil
), and others only work for rounding to 0.5 (which is what the question asked, yes). Here's a simple method that correctly rounds to the nearest arbitrary double, with a check to assure that it's a positive number.