2

Hello I should round up my float value to successive .25 value. Example:

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

I tried use Math.round(myFloat*4)/4f; but it return the nearest, so if I have:

1.1 return 1 and not 1.25
LorenzoBerti
  • 6,704
  • 8
  • 47
  • 89

3 Answers3

4

You should be using Math.ceil() instead of Math.round():

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

Closely related: Java - rounding by quarter intervals

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    If I were you though I'd divide by `4.0`. The wise owls at Java decided that `ceil` should return a `double` cf. `round` returning `long`. If you had used `round` then the division would happen in integer arithmetic! *Just in case* a refactorer changes your formula to `round`, I'd doubly force the expression to be calculated in floating point. – Bathsheba Oct 21 '16 at 07:20
2

You almost had it. To round up, use Math.ceil(myFloat*4)/4f instead of Math.round

Sofie Vos
  • 383
  • 2
  • 12
0

You need to implement your own round off logic.

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;
}
Sanjeet
  • 2,385
  • 1
  • 13
  • 22
  • A nice idea, but this can "go off" due to floating point. It's not a good idea to interchange `round`, `floor`, and `ceil` using additive constants. The accepted answer in http://stackoverflow.com/questions/9902968/why-does-math-round0-49999999999999994-return-1 explains this well. – Bathsheba Oct 21 '16 at 07:04