Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you round down to the nearest multiple of 20in Java?

Please keep in mind I only want to round DOWN to the nearest multiple of 20, never up.

  • 22 --> 20
  • 45 --> 40
  • 69.5 --> 60
  • 60 --> 60

Thanks a lot!

like image 600
Hamoush Avatar asked Nov 27 '14 16:11

Hamoush


2 Answers

One solution would be to subtract the results of modulo 20 (which is the remainder from division by 20) from the initial value. Something like,

double[] in = { 22, 45, 69.5, 60 };
for (double d : in) {
    int v = (int) d;
    v -= v % 20;
    System.out.printf("%.1f --> %d%n", d, v);
}

Output is

22.0 --> 20
45.0 --> 40
69.5 --> 60
60.0 --> 60
like image 197
Elliott Frisch Avatar answered Oct 21 '22 06:10

Elliott Frisch


public static Integer round20(Integer b){
        return b - (b%20);
    }
like image 34
gasparms Avatar answered Oct 21 '22 07:10

gasparms