Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Suppose I have Long someLong = 1004L. What efficient method can I use to round this down to 1000L? Note that I do not actually know that someLong == 1004L so I can't simply do someLong -= 4L;. I need a generalizable method. I also want the ability to round down to each 5 instead of each 10, for example a function to round to 1005L (since if we're rounding by 5's then it'll round up instead of down).

More examples .. It could be that I have 1926L and I want to round to 5 meaning I need 1925L. Or I need to round to 10 meaning I need 1930L.

like image 534
user2763361 Avatar asked Dec 07 '22 02:12

user2763361


2 Answers

This is very simple.

If you want to round always down:

Your required formula is:

someLong-someLong%10

It is because someLong%10 is the remainder of someLong divided by 10. If you get this from the original number, you get the downrounded value, which you wanted.

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

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


If you want to round always up:

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

someLong+9-(someLong+9)%10

If you want to round always to the middle:

...also you want to round to the nearest neightbor. Then you first add the half of the required interval, then round always down. For example, for 10 it is:

someLong+5-(someLong+5)%10
like image 103
peterh Avatar answered Dec 08 '22 16:12

peterh


If you want to round a value towards the nearest multiple of step using the semantics of BigDecimal.ROUND_HALF_UP (if exactly halfway between two steps, round up), the necessary calculations are:

val += step/2;
val -= val%step;
like image 44
jarnbjo Avatar answered Dec 08 '22 15:12

jarnbjo