【问题标题】:Java round to nearest .5 [duplicate]Java四舍五入到最接近的0.5 [重复]
【发布时间】:2014-06-20 09:48:04
【问题描述】:

这在 Java 中怎么可能?

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

例如:

1.1 应该四舍五入到 1.0

1.3 应该四舍五入到 1.5

2.5 应该四舍五入到 2.5

3.223920 应该舍入到 3.0

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

【问题讨论】:

  • 乘以二,四舍五入,最后除以二
  • 我在 Google 中尝试了无数不同的输入,但没有给我那个帖子。
  • 我用谷歌搜索了这个:google.com/… 但无论如何。感谢您的回答。
  • Google 会忽略标点符号,因此您实际上是在搜索“在 java 中四舍五入到最接近的 5”:support.google.com/websearch/answer/2466433?hl=en

标签: java decimal rounding


【解决方案1】:

@SamiKorhonen 在评论中说:

乘以二,四舍五入,最后除以二

这就是代码:

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

【讨论】:

  • 我喜欢这个代码...我会放入我的库存...谢谢
  • 请记住,Math.round(-83.25*10)/10f 和 Math.round(83.25*10)/10f 会给你 -83.2 和 83.3 的结果。
【解决方案2】:

一般的解决办法是

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

在你的情况下,你可以这样做

double d = roundToFraction(x, 2);

四舍五入到小数点后两位

double d = roundToFraction(x, 100);

【讨论】:

  • 如果我想四舍五入到最接近的 0.75 怎么办?我会通过 4/3 而不是 2 吗?谢谢
  • @theprogrammer 最接近 0.75 的倍数,例如1.5、2.25、3.00。如果您想要以 0.75 结尾的最接近的数字,请减去 0.75,将其四舍五入并加回 0.75。
【解决方案3】:

虽然它不是那么优雅,但您可以创建自己的 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    相关资源
    最近更新 更多