简体   繁体   English

四舍五入到最近的一半(不是最近的整数)

[英]Rounding to the nearest half (NOT the nearest whole)

I need to round a double to the nearest .5. 我需要将一个双舍入到最接近的.5。 I do not want to end up with a number ending in .0. 不想在.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. 我已搜索周围有点,但似乎每个人都想圆与0.5最接近的倍数 ,而不仅仅是最近的一半,但不是全部。 I tried dividing by .5, rounding that, and multiplying by .5, but this still rounds to multiples of .5. 我尝试将.5除以四舍五入,并乘以.5,但这仍然是.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). 在此之后添加或减去.5并不总是围绕它应该去的数字(当你应该减去时可以添加)。

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(num * 2) / 2.0f应该解决四舍五入到最接近的半问题:

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: 四舍五入到任何分数f:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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