简体   繁体   中英

Rounding to the nearest half (NOT the nearest whole)

I need to round a double to the nearest .5. I do not want to end up with a number ending in .0.

I've searched around for a bit, but it seems like everyone wants to round to the nearest multiple of .5 rather than just the nearest half but not whole. I tried dividing by .5, rounding that, and multiplying by .5, but this still rounds to multiples of .5. Adding or subtracting .5 after this will not always round the number where it should go (you might add when you should have subtracted).

Any help would be greatly appreciated.

I think that Math.round(num * 2) / 2.0f should solve the rounding to the nearest half problem:

Math.round(3.9 * 2) / 2.0f == 8 / 2.0f = 4.0
Math.round(3.6 * 2) / 2.0f == 7 / 2.0f = 3.5
Math.round(3.1 * 2) / 2.0f == 6 / 2.0f = 3.0

Subtract, round and add...

Math.round(value - 0.5) + 0.5

Another working way mentioned in question's comments:

Math.floor(value) + 0.5

rounding to any fraction f:

double f = 0.5;
double rounded = f * Math.round(x/f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM