1

I'm running into following issue...

Does an already 'built-in' function exists in java to round given random numbers to the closest lower quarter value.

These are the given random numbers:

2.00 -> 2.00
2.24 -> 2.00
2.25 -> 2.25
2.49 -> 2.25
2.50 -> 2.50
2.74 -> 2.50
2.75 -> 2.75
2.99 -> 2.75
3.00 -> 3.00
Hiran
  • 287
  • 4
  • 19

3 Answers3

7

You can multiply the value by 4 then floor it then divide by 4.

public static double quarterRound(double v){
   return Math.floor(v*4)/4;
}
toskv
  • 28,720
  • 7
  • 71
  • 71
3

You need to round to quarters so:

  • Multiply by 4
  • Floor to next int
  • Divide by 4

Note that if you reliable values it is better to works with BigDecimal instead of primitive values (double or float). The algorithm stay the same.

Davide Lorenzo MARINO
  • 25,114
  • 4
  • 37
  • 52
  • In this particular instance, binary floating-point may be better: multiplication by 4 and division by 4 are exact operations for binary floating-point (assuming that overflow and underflow are avoided), but might incur rounding errors for decimal floating-point. The floor operation is also exact (for both decimal and binary floating-point). – Mark Dickinson Aug 28 '15 at 16:33
0

Try this:

double value = 2.99D;
value = (double)(int)(value * 4) / 4;
spongebob
  • 8,552
  • 13
  • 45
  • 80
Stan Fad
  • 984
  • 10
  • 21