gpt4 book ai didi

c# - 大数字的 IsNumeric Helper 方法

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:19 25 4
gpt4 key购买 nike

我正在尝试创建一个简单的辅助函数来确定一个数字是否是真正的数字。显然它应该能够处理“null”、负数,而我正在尝试在没有 VB 的 IsNumeric 帮助的情况下执行此操作。刚刚学习了 LINQ,我认为那将是完美的。

我想要的另一件事是能够传递字符串、整数、长整型或任何其他类型,所以我认为将“对象”作为参数才是我真正想要的。当然,我总是可以在调用辅助方法之前将类型转换为字符串,但这可能吗?

这是我目前的代码,我需要做的就是能够更改参数!我无法想象这是不可能的……有什么想法吗?

private static bool IsNumeric(string input)
{
if (input == null) throw new ArgumentNullException("input");
if (string.IsNullOrEmpty(input)) return false;

int periodCount = 0; //accept a string w/ 1dec to support values w/ a float

return input.Trim()
.ToCharArray()
.Where(c =>
{
if (c == '.') periodCount++;
return Char.IsDigit(c) && periodCount <= 1;
})
.Count() == input.Trim().Length;
}

最佳答案

也许吧?

private static bool IsNumeric<T>(T input)
{
double d;
return double.TryParse(input.ToString(), NumberStyles.Any,CultureInfo.InvariantCulture, out d);
}

bool b1 = IsNumeric(1); //<-- true
bool b2 = IsNumeric(1.0); //<-- true
bool b3 = IsNumeric("a"); //<-- false
bool b4 = IsNumeric("3E+10"); //<-- true
bool b5 = IsNumeric("1,234,567.0"); //<-- true

关于c# - 大数字的 IsNumeric Helper 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16379137/

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