Java 四舍五入到最接近的 .5

标签 java decimal rounding

<分区>

这在 Java 中如何实现?

我有一个 float ,我想将它四舍五入到最接近的 .5。

例如:

1.1 应该四舍五入到 1.0

1.3 应该四舍五入到 1.5

2.5 应四舍五入为 2.5

3.223920 应四舍五入为 3.0

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

最佳答案

@SamiKorhonen 在评论中这样说:

Multiply by two, round and finally divide by two

这就是代码:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23449662/

相关文章:

java - 使用 Observable.timeout 超时后会发生什么?

java - 如何以编程方式访问 spring.application.instance_id?

c - 如何让 strtok() 返回十进制数而不是整数?

bash - 四舍五入 float bash

excel - 是否可以根据范围在excel中四舍五入到不同的小数位?

java - 如何在Cucumber中的glue属性中提及完全分类的类名

java - 不同实体管理器之间共享 JPA 实体

c# - 加法的十进制顺序影响结果

c++ - 由于舍入行为导致 float 和错误结果

go - Go中四舍五入到小数点后2位