Java - 如何将float(或BigDecimal)值向上舍入0.5?

mas*_*san 6 java rounding

看似简单的问题,但我真的很厌倦数学和网上的几个例子,我搜索似乎不适合我.(结果只返回与输入相同的值等)

例如..但它在C中不是Java Round to Next .05 in C.

所以我的目标是我有%.1f格式float或者double或者big decimal想要将它四舍五入到最接近的.5

example:

1.3 --> 1.5
5.5 --> 5.5
2.4 --> 2.5
3.6 --> 4.0
7.9 --> 8.0
Run Code Online (Sandbox Code Playgroud)

我尝试了以下示例,但没有工作:(下面只输出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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*els 17

这是一个简单的方法:

public static float roundToHalf(float x) {
    return (float) (Math.ceil(x * 2) / 2);
}
Run Code Online (Sandbox Code Playgroud)

这使价值翻倍,达到上限,并将其削减一半.


Nic*_*ick 8

乘以(以及之后除以)2而不是20,应该可以解决问题.


Ber*_*t F 5

 double nearestPoint5 = Math.ceil(d * 2) / 2;
Run Code Online (Sandbox Code Playgroud)


She*_*men 5

以下公式不适用于像2.16这样的数字

public static float roundToHalf(float x) {
  return (float) (Math.ceil(x * 2) / 2);
}
Run Code Online (Sandbox Code Playgroud)

正确答案应该是2.0,但是上述方法给出的是2.5

正确的代码应为:

public static double round(float d)
{
    return 0.5 * Math.round(d * 2);
}
Run Code Online (Sandbox Code Playgroud)