gpt4 book ai didi

T-SQL轮函数的C#实现

转载 作者:行者123 更新时间:2023-11-30 20:08:30 25 4
gpt4 key购买 nike

我试图在 C# 中重现 T-SQL Round function 的行为当使用截断函数时。

这是我试图在 C# 中重现的 SQL 行为:

SELECT ROUND(150.757,2,0) -- 150.76
SELECT ROUND(150.757,2,1) -- 150.75

SELECT ROUND(150.747,2,0) -- 150.75
SELECT ROUND(150.747,2,1) -- 150.74

System.Math 中,我尝试使用了两种方法。

第一个,Math.Truncate 只截断整个部分,所以它对我没有帮助。

另一种方法是Math.Round

此方法有 2 个有趣的重载。

Math.Round(decimal,int)
Math.Round(decimal,int,System.MidpointRounding)

MidpointRounding 枚举选项是:

System.MidpointRounding.AwayFromZero
// When a number is halfway between two others,
// it is rounded toward the nearest number that is away from zero.

System.MidpointRounding.ToEven
// When a number is halfway between two others,
// it is rounded toward the nearest even number.

使用与 SQL 相同的数据执行 Math.Round 的两个重载,我得到以下结果:

Math.Round(150.757, 2, MidpointRounding.AwayFromZero) // 150.76
Math.Round(150.757, 2, MidpointRounding.ToEven) // 150.76

Math.Round(150.747, 2, MidpointRounding.AwayFromZero) // 150.75
Math.Round(150.747, 2, MidpointRounding.ToEven) // 150.75

鉴于 MidpointRounding 都不能解决我的问题,在 C# 中重现 T-SQL 函数的最佳方法是什么?

更新:

执行 Paul 的回答后,我注意到 T-SQL ROUND 函数有一个额外的奇怪行为:

SELECT ROUND(150.747,-2,1) // 100
SELECT ROUND(150.747,-2) // 200

我编辑了 Paul 的回答以包括对这种边缘情况的支持。

最佳答案

我想有人会想出更好的方法,但这当然是可行的方法!

using System;

static class Program
{
static void Main(string[] args)
{
Console.WriteLine(150.757.TruncateWithDecimalPlaces(2));
Console.WriteLine(150.747.TruncateWithDecimalPlaces(2));
Console.Read();
}
public static double TruncateWithDecimalPlaces(this double input, int decimalPlaces)
{
double factor = Math.Pow(10, decimalPlaces);
return Math.Truncate(input*factor)/factor;
}
}

输出:

150.75
150.74

更完整的实现看起来像这样:

public static double Round(double input, int decimalPlaces, int roundType = 0)
{
double factor = Math.Pow(10, decimalPlaces);
if (roundType == 0)
{
if (decimalPlaces >= 0)
{
return Math.Round(input, decimalPlaces);
}
return Math.Round(input * factor) / factor;
}
return Math.Truncate(input * factor) / factor;
}

关于T-SQL轮函数的C#实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7099996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com