Java 四舍五入到最接近的 0.5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23449662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:03:00  来源:igfitidea点击:

Java round to nearest .5

javadecimalrounding

提问by user1513171

How is this possible in Java?

这在 Java 中怎么可能?

I have a float and I'd like to round it to the nearest .5.

我有一个浮点数,我想把它四舍五入到最接近的 0.5。

For example:

例如:

1.1 should round to 1.0

1.1 应该四舍五入到 1.0

1.3 should round to 1.5

1.3 应该四舍五入到 1.5

2.5 should round to 2.5

2.5 应该四舍五入到 2.5

3.223920 should round to 3.0

3.223920 应该四舍五入到 3.0

EDIT: Also, I don't just want the string representation, I want an actual float to work with after that.

编辑:另外,我不只是想要字符串表示,我想要一个实际的浮点数。

采纳答案by Michael Yaworski

@SamiKorhonen said this in a comment:

@SamiKorhonen 在评论中说:

Multiply by two, round and finally divide by two

乘以二,圆,最后除以二

So this is that code:

所以这是代码:

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);
}

Output:

输出:

1.0
1.5
2.5
3.0
3.0

回答by Peter Lawrey

The general solution is

一般的解决办法是

public static double roundToFraction(double x, long fraction) {
    return (double) Math.round(x * fraction) / fraction;
}

In your case, you can do

在你的情况下,你可以做

double d = roundToFraction(x, 2);

to round to two decimal places

四舍五入到小数点后两位

double d = roundToFraction(x, 100);

回答by Kostas Chalkias

Although it is not that elegant, you could create your own Round function similarly to the following (it works for positive numbers, it needs some additions to support negatives):

虽然它不是那么优雅,但您可以创建自己的 Round 函数,类似于以下内容(它适用于正数,它需要一些添加来支持负数):

public static double roundHalf(double number) {
    double diff = number - (int)number;
    if (diff < 0.25) return (int)number;
    else if (diff < 0.75) return (int)number + 0.5;
    else return (int)number + 1;
}