本文介绍了Java舍入到最近的.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这在Java中怎么可能?
How is this possible in Java?
我有一个浮点数,我想把它四舍五入到最接近的.5。
I have a float and I'd like to round it to the nearest .5.
例如:
1.1应该舍入到1.0
1.1 should round to 1.0
1.3应该舍入到1.5
1.3 should round to 1.5
2.5应该舍入到2.5
2.5 should round to 2.5
3.223920应该舍入到3.0
3.223920 should round to 3.0
编辑:另外,我不只是想要字符串表示,我想在之后使用实际的浮点数。
EDIT: Also, I don't just want the string representation, I want an actual float to work with after that.
解决方案
@SamiKorhonen在评论中说:
@SamiKorhonen said this in a comment:
所以这就是代码:
public static double roundToHalf(double d) {
return Math.round(d * 2) / 2.0;
}
public static void main(String[] args) {
double d1 = roundToHalf(1.1);
double d2 = roundToHalf(1.3);
double d3 = roundToHalf(2.5);
double d4 = roundToHalf(3.223920);
double d5 = roundToHalf(3);
System.out.println(d1);
System.out.println(d2);
System.out.println(d3);
System.out.println(d4);
System.out.println(d5);
}
输出:
1.0
1.5
2.5
3.0
3.0
这篇关于Java舍入到最近的.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!