【问题标题】:Round up float .25向上取整浮动 0.25
【发布时间】:2016-10-21 06:59:18
【问题描述】:

您好,我应该将浮点值四舍五入为连续的 0.25 值。 示例:

0.123 =>  0.25
0.27 => 0.5
0.23 => 0.25
0.78 => 1
0.73 => 0.75
10.20 => 10.25
10.28 => 10.5

我尝试使用Math.round(myFloat*4)/4f;,但它返回最近的,所以如果我有:

1.1 return 1 and not 1.25

【问题讨论】:

  • Math.ceil(myFloat*4)/4f
  • ceil怎么样?

标签: android rounding


【解决方案1】:

您应该使用Math.ceil() 而不是Math.round():

Math.ceil(myFloat*4) / 4.0d;

密切相关:Java - rounding by quarter intervals

【讨论】:

  • 如果我是你,我会除以4.0。 Java 的聪明猫头鹰决定 ceil 应该返回 double cf。 round 返回long。如果您使用了round,那么除法将在整数算术中发生! 以防万一重构器将您的公式更改为round,我会加倍强制表达式以浮点数计算。
【解决方案2】:

你几乎拥有它。要四舍五入,请使用 Math.ceil(myFloat*4)/4f 而不是 Math.round

【讨论】:

    【解决方案3】:

    您需要实现自己的舍入逻辑。

    public static double roundOffValue(double value) {
        double d = (double) Math.round(value * 10) / 10;
        double iPart = (long) d;
        double fPart = value - iPart;
        if (value == 0.0) {
            return 0;
        }else if(fPart == 0.0){
            return iPart;
        }else if (fPart <= 0.25) {
            iPart = iPart + 0.25;
        } else if (fPart <= 0.5) {
            iPart = iPart + 0.5;
        } else if (fPart < 0.75) {
            iPart = iPart + 0.75;
        } else {
            iPart = iPart + 1;
        }
        return iPart;
    }
    

    【讨论】:

    • 一个好主意,但由于浮点,这可能会“失败”。使用加法常数交换 roundfloorceil 不是一个好主意。 stackoverflow.com/questions/9902968/… 中接受的答案很好地解释了这一点。
    猜你喜欢
    • 2013-01-15
    • 2012-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多