我有一些Input(双精度值),例如4329,我必须将其四舍五入为特定数字:
4200、5200、6200、7200 ... 25200
我希望它总是四舍五入,以便4329变为5200。
目前,我使用21个ifs来做到这一点,但这似乎不是一个好主意。
答案 0 :(得分:4)
那呢:
using System.Linq;
(...)
var limits = new []{4200, 4400,5200,8201,9200,12000,12200};
var number = 300;
var ceiled = limits.First(l => l >= number);
答案 1 :(得分:2)
使用Math.Ceiling
和Math.Max
的组合,您可以通过以下方法来实现:减去起始数字,除以区间,然后取上限,然后以0.0
取最大值,然后取消除法和偏移:
double firstThreshold = 4200;
double interval = 1000;
double output = Math.Max(
0.0,
Math.Ceiling( (input - firstThreshold) / interval )
) * interval + firstThreshold;
如果输入大于25200,会发生什么情况还不清楚,因此,如果这是一个很难的最大值,则可以根据需要使用Math.Min
将最大值设置为25200:
double firstThreshold = 4200;
double interval = 1000;
double maxValue = 25200;
double output = Math.Min(maxValue,
Math.Max(
0.0,
Math.Ceiling( (input - firstThreshold ) / interval )
) * interval + firstThreshold);
这些不需要遍历或填充列表,因此恒定时间也是如此。
答案 2 :(得分:1)
我想根据您的问题标题[回合]推荐这种方法
不是[向上舍入]
如果是[向上舍入],那么tymtam的答案将是合适的。
导入区域
using System.Linq;
using System.Math;
代码区
// Target List Which you will get as a result
List<int> Targets = new List<int>();
Targets.AddRange(new int[] { 4200, 5200, 6200, 7200, 9200, 11200, 11700, 15300, 17200, 20000, 23000, 25200 });
// Target value which you will check
int InputNo = 4329;
// Region for Round
{
// This print 4200 for 4329
// and 15300 for 15400
// Check differences between Targets' elements and InputNo
List<int> Diffs = Targets.Select(x => Math.Abs(x - InputNo)).ToList();
int index = Diffs.IndexOf(Diffs.Min());
// Print Result
Console.WriteLine("Round Result => " + Targets[index]);
}
// Region for Round Up
{
int Result = -1;
try
{
Result = Targets.Where(x => (x >= InputNo)).First();
}
catch
{
Result = Targets.Max();
}
// This prints Round up values.
// if InputNo is bigger than any Elements, it'll be return Max values of elements
Console.WriteLine("Round Up Result => " + Result);
}
答案 3 :(得分:1)
如果您经常这样做,则可以创建一个扩展方法
给出
public static class Extensions
{
public static int RoundTo(this int source, params int[] values)
=> values.OrderBy(x => x).First(x => x >= source);
}
用法1
var input = 4329;
var result = input.RoundTo(4200, 5200, 6200, 7200, 25200);
用法2
var array = new[] { 4200, 5200, 6200, 7200, 25200 };
var input = 4329;
var result = input.RoundTo(array);
输出
5200
5200
如果您需要的支持超过 int ,请添加胡椒粉和盐调味
public static int RoundTo(this double source, params int[] values)
=> values.OrderBy(x => x).First(x => x >= source);
public static int RoundTo(this decimal source, params int[] values)
=> values.OrderBy(x => x).First(x => x >= source);
答案 4 :(得分:0)
您可以尝试:
Func<double, double> roundingFunc = (double x) => Math.Ceiling((x - 200) / 1000) * 1000 + 200;