舍入到最近的一半(不是最近的整数) [英] Rounding to the nearest half (NOT the nearest whole)

查看:162
本文介绍了舍入到最近的一半(不是最近的整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个双倍到最近的.5。我不想想要以.0结尾的号码。

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

我已经搜索了一下,但似乎每个人都希望绕到最接近的多个的.5而不是最近的一半而不是整个。我尝试除以.5,舍入,乘以.5,但这仍然是.5的倍数。在此之后添加或减去.5将不总是舍入它应该去的数字(你应该减去的时候你可以添加)。

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.

推荐答案

减去,轮并添加...

Subtract, round and add...

Math.round(value - 0.5) + 0.5

另一种工作方式提到有问题的意见:

Another working way mentioned in question's comments:

Math.floor(value) + 0.5

这篇关于舍入到最近的一半(不是最近的整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆