Java: round to nearest multiple of 5 (either up or down)

2022-08-31 16:16:54

I need to round a number to nearest multiple of 5 (either up or down). For example, here are the list of numbers and the number next to it that it needs to round up/down to.

12.5  10
62.1  60
68.3  70
74.5  75
80.7  80

Numbers will only be positive.


答案 1

haven't tested it, but should work5*(Math.round(f/5));


答案 2

Nearest Multiple of 5 for Upper value

5*(Math.ceil(Math.abs(number/5)));

for Lower Value

5*(Math.floor(Math.abs(number/5)));

it gives Positive value only.