四舍五入到下个季度 [英] Round up to next quarter

查看:118
本文介绍了四舍五入到下个季度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想圆一个数字为下一个季度(即2.1四舍五入为2.25)。我明白,我可以用得到就近季度 Math.Round(NU​​M * 4)/ 4 ,但我想在此展开,使其始终向上舍入到下个季度。

I would like to round a number up to the next quarter (i.e. 2.1 rounds to 2.25). I understand that I can get the nearest quarter by using Math.Round(num * 4) / 4, but I would like to expand on this so that it always rounds up to the next quarter.

到目前为止,我唯一的解决方案涉及if块使用,但我想先竭一行程序算法的方法,试图让事情变得简单。

So far my only solutions involve using if blocks, but I would like to exhaust the one-liner algorithm approach first to try to keep things simple.

这在技术上是语言无关,但在这种情况下,我使用C#。

This is technically language independent, but in this case I am using C#.

需要明确的是,下面是我想要的例子:

To be clear, below are examples of what I want:

  • 2.0保持为2.0
  • 在2.01 - 2.24圆达2.25
  • 2.25保持为2.25
  • 在2.26 - 2.49圆高达2.5
  • 等等...

推荐答案

怎么这样呢?

return Math.Ceiling(x * 4) / 4;

下面是一个解释。假设你想四舍五入到最接近的整数。这很简单,这正是 Math.Ceiling 一样。

Here's an explanation. Say you wanted to round up to the nearest whole number. That's easy—it's exactly what Math.Ceiling does.

好了,我们已经有一个算法,拥有我们想要的行为。这只是找错不断。

OK, so we already have an algorithm that has the behavior we want. It's just got the wrong constant.

我们可以解决这个由映射我们的投入,思考每一个季度作为映射到一个整体(这将正确地重新present 0.25的倍数):

We can get around this by "mapping" our input, thinking of every "quarter" as mapping to a whole (which would rightly represent the multiple of 0.25):

0.25 => 1
0.50 => 2
0.75 => 3
1.00 => 4
1.25 => 5

&放大器; C,与放大器; C。

&c., &c.

下面的映射关系是直接的。从左向右走,由4乘以从右至左,除以4,注意事项去的每一个值> = 0.25 LT; 0.5将映射到一些东西1和2之间,这正是我们想要的,因为 Math.Ceiling 将四舍五入到2在这种情况下,我们就可以映射回0.5。

The mapping relationship here is straightforward. To go from left to right, multiply by 4. To go from right to left, divide by 4. Notice every value >= 0.25 < 0.5 will map to something between 1 and 2, which is what we want because Math.Ceiling will round up to 2 in this case, which we can then map back to 0.5.

所以基本上我们我们的输入映射到一个值,与已经实现的算法的工作(<$ C C $> Math.Ceiling );那么,我们的结果返回映射到的一组值从我们的投入就来了。

So essentially we map our input to a value that works with the already-implemented algorithm (Math.Ceiling); then we map the result back to the set of values our input came from.

有意义吗?

这篇关于四舍五入到下个季度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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