Round long from 1004L to 1000L (or from 1006L to 1010L)

Suppose I have one Long someLong = 1004L. What effective method can be used to round to 1000L? Please note that I really don’t know what someLong == 1004L, so I just can’t do it someLong -= 4L;. I need a generic method. I also need the ability to round to each 5instead of each 10, for example, the round to function 1005L(since if we round to 5, then it will round, not down).

Additional examples. Perhaps I have 1926L, and I want to round to 5, which means what I need 1925L. Or do I need to round to 10what I need 1930L.

+4
source share
6 answers

It is very simple.

If you want to always turn down :

Your required formula:

someLong-someLong%10

This is because someLong%10- this is the remainder of someLongdivided by 10. If you get this from the original number, you will get the desired value.

The generalization is also simple: you can use 100 or even 13 if you want.

If you want to round in the other direction (for example, always round up or always to the middle), then first add something to this number, and then round always down.


If you want to always round:

Then first you need to add 9, and then the round is always down.

someLong+9-(someLong+9)%10

:

... neightbor. , . , 10 :

someLong+5-(someLong+5)%10
+7

:

double a=1002l;
double b=a/10;

a=Math.round(b)*10;

System.out.println("Double round of value : "+a);
+2

k ( ):

public static long round(long toRound, long k) {
    long times = toRound / k;
    long reminder = toRound % k;
    if (reminder < k / 2)  {
        return k * times;
    } else {
        return k * (times + 1);
    }
}

(reminder < k / 2 = > (2 * reminder / k) < 1:

public static long round(long toRound, long k) {
    long times = toRound / k;
    long reminder = toRound % k;
    return k * (times + ((2 * reminder) / k));
}
+2

value step, BigDecimal.ROUND_HALF_UP ( , ), :

val += step/2;
val -= val%step;
+2
myFloor(long n, int m) {
  return n - (n % m);
}


myRound(long n, int m) {
  int i = (n % m) >= (m / 2) ? m : 0;
  return n + i - (n % m);
}

m 10 , 5 , ...

+1

, :

public static void main(String[] args) {
    Long n   = 1004L;
    Long n2  = 1005L;

    n = round(n);
    n2 = round(n2);

    System.out.println(n);
    System.out.println(n2);
}

private static Long round(Long n) {
    if (n%10 <=4) {
        return n -=n%10;
    } else {
        return n += (10-n%10);
    }
}
+1

Source: https://habr.com/ru/post/1536104/


All Articles