Określ, czy ciąg znaków jest liczbą
Jeśli mam te struny:
"abc"
=false
"123"
=true
"ab2"
=false
Czy istnieje polecenie, jak IsNumeric()
lub coś innego, które może określić, czy łańcuch znaków jest poprawną liczbą?
25 answers
int n;
bool isNumeric = int.TryParse("123", out n);
Update od C # 7:
var isNumeric = int.TryParse("123", out int n);
Lub jeśli nie potrzebujesz numeru, możesz odrzucić parametr out
var isNumeric = int.TryParse("123", out _);
var s można zastąpić odpowiednimi typami!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-14 13:37:06
Zwróci true, Jeśli input
to wszystkie liczby. Nie wiem, czy jest lepszy niż TryParse
, ale zadziała.
Regex.IsMatch(input, @"^\d+$")
Jeśli chcesz tylko wiedzieć, czy ma jedną lub więcej cyfr zmieszanych ze znakami, zostaw ^
+
i $
.
Regex.IsMatch(input, @"\d")
Edit: Właściwie myślę, że jest to lepsze niż TryParse, ponieważ bardzo długi ciąg może potencjalnie przepełnić TryParse.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-21 19:08:07
Możesz również użyć:
stringTest.All(char.IsDigit);
Zwróci true
dla wszystkich cyfr (nie float
) i false
, jeśli łańcuch wejściowy jest dowolnie alfanumeryczny.
Uwaga: stringTest
nie powinien być pustym ciągiem znaków, ponieważ przejdzie to test bycia liczbowym.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-30 09:53:38
Użyłem tej funkcji kilka razy:
public static bool IsNumeric(object Expression)
{
double retNum;
bool isNum = Double.TryParse(Convert.ToString(Expression), System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);
return isNum;
}
Ale można też użyć;
bool b1 = Microsoft.VisualBasic.Information.IsNumeric("1"); //true
bool b2 = Microsoft.VisualBasic.Information.IsNumeric("1aa"); // false
From Benchmarking IsNumeric Options
(źródło: aspalliance.com)
(źródło: aspalliance.com)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-17 20:01:36
Jest to prawdopodobnie najlepsza opcja w C#.
Jeśli chcesz wiedzieć, czy łańcuch zawiera liczbę całkowitą (integer):
string someString;
// ...
int myInt;
bool isNumerical = int.TryParse(someString, out myInt);
Metoda TryParse spróbuje przekonwertować łańcuch znaków na liczbę (integer) i jeśli się powiedzie, zwróci true i umieści odpowiednią liczbę w myInt. Jeśli nie może, zwraca false.
Rozwiązania wykorzystujące alternatywę int.Parse(someString)
pokazaną w innych odpowiedziach działają, ale są znacznie wolniejsze, ponieważ rzucanie wyjątków jest bardzo kosztowne. TryParse(...)
dodano do języka C# w wersji 2, a do tego czasu nie miałeś wyboru. Teraz to robisz: dlatego powinieneś unikać Parse()
alternatywy.
Jeśli chcesz zaakceptować liczby dziesiętne, Klasa dziesiętna ma również metodę .TryParse(...)
. Zastąp int przez decimal w powyższej dyskusji i obowiązują te same zasady.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-31 20:01:58
Możesz zawsze użyć wbudowanych metod TryParse dla wielu typów danych, aby sprawdzić, czy dany łańcuch przejdzie.
Przykład.
decimal myDec;
var Result = decimal.TryParse("123", out myDec);
Wynik byłby wtedy = True
decimal myDec;
var Result = decimal.TryParse("abc", out myDec);
Wynik byłby wtedy = False
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-27 14:37:59
W przypadku, gdy nie chcesz używać int.Parse lub double.Parse, możesz toczyć własne z czymś takim:
public static class Extensions
{
public static bool IsNumeric(this string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c) && c != '.')
{
return false;
}
}
return true;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-21 18:13:20
Jeśli chcesz złapać szersze spektrum liczb, a la PHP is_numeric , możesz użyć następującego:
// From PHP documentation for is_numeric
// (http://php.net/manual/en/function.is-numeric.php)
// Finds whether the given variable is numeric.
// Numeric strings consist of optional sign, any number of digits, optional decimal part and optional
// exponential part. Thus +0123.45e6 is a valid numeric value.
// Hexadecimal (e.g. 0xf4c3b00c), Binary (e.g. 0b10100111001), Octal (e.g. 0777) notation is allowed too but
// only without sign, decimal and exponential part.
static readonly Regex _isNumericRegex =
new Regex( "^(" +
/*Hex*/ @"0x[0-9a-f]+" + "|" +
/*Bin*/ @"0b[01]+" + "|" +
/*Oct*/ @"0[0-7]*" + "|" +
/*Dec*/ @"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" +
")$" );
static bool IsNumeric( string value )
{
return _isNumericRegex.IsMatch( value );
}
Test Jednostkowy:
static void IsNumericTest()
{
string[] l_unitTests = new string[] {
"123", /* TRUE */
"abc", /* FALSE */
"12.3", /* TRUE */
"+12.3", /* TRUE */
"-12.3", /* TRUE */
"1.23e2", /* TRUE */
"-1e23", /* TRUE */
"1.2ef", /* FALSE */
"0x0", /* TRUE */
"0xfff", /* TRUE */
"0xf1f", /* TRUE */
"0xf1g", /* FALSE */
"0123", /* TRUE */
"0999", /* FALSE (not octal) */
"+0999", /* TRUE (forced decimal) */
"0b0101", /* TRUE */
"0b0102" /* FALSE */
};
foreach ( string l_unitTest in l_unitTests )
Console.WriteLine( l_unitTest + " => " + IsNumeric( l_unitTest ).ToString() );
Console.ReadKey( true );
}
Należy pamiętać, że tylko dlatego, że wartość jest numeryczna, nie oznacza, że można ją przekonwertować na typ numeryczny. Na przykład, "999999999999999999999999999999.9999999999"
jest poprawną wartością liczbową perfeclty, ale nie będzie pasować do typu numerycznego. NET (czyli nie zdefiniowanego w bibliotece standardowej).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-25 13:35:45
Wiem, że to stary wątek, ale żadna z odpowiedzi nie zrobiła tego za mnie - albo nieefektywna, albo nie zamknięta dla łatwego ponownego użycia. Chciałem również upewnić się, że zwraca false, jeśli łańcuch jest pusty lub null. W tym przypadku TryParse zwraca true (pusty łańcuch nie powoduje błędu podczas parsowania jako liczba). Oto moja metoda rozszerzenia ciągu:
public static class Extensions
{
/// <summary>
/// Returns true if string is numeric and not empty or null or whitespace.
/// Determines if string is numeric by parsing as Double
/// </summary>
/// <param name="str"></param>
/// <param name="style">Optional style - defaults to NumberStyles.Number (leading and trailing whitespace, leading and trailing sign, decimal point and thousands separator) </param>
/// <param name="culture">Optional CultureInfo - defaults to InvariantCulture</param>
/// <returns></returns>
public static bool IsNumeric(this string str, NumberStyles style = NumberStyles.Number,
CultureInfo culture = null)
{
double num;
if (culture == null) culture = CultureInfo.InvariantCulture;
return Double.TryParse(str, style, culture, out num) && !String.IsNullOrWhiteSpace(str);
}
}
Prosty w użyciu:
var mystring = "1234.56789";
var test = mystring.IsNumeric();
Lub, jeśli chcesz przetestować inne typy liczb, możesz określić 'styl'. Więc do nawrócenia Liczba z wykładnikiem, można użyć:
var mystring = "5.2453232E6";
var test = mystring.IsNumeric(style: NumberStyles.AllowExponent);
Lub aby przetestować potencjalny ciąg sześciokątny, możesz użyć:
var mystring = "0xF67AB2";
var test = mystring.IsNumeric(style: NumberStyles.HexNumber)
Opcjonalny parametr 'culture' może być używany w podobny sposób.
Jest to ograniczone przez to, że nie jest w stanie konwertować łańcuchów, które są zbyt duże, aby mogły być zawarte w podwójnym, ale jest to ograniczone Wymaganie i myślę, że jeśli pracujesz z liczbami większymi niż to, prawdopodobnie będziesz potrzebować dodatkowych wyspecjalizowanych funkcji obsługi liczb.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 09:44:35
Możesz użyć TryParse, aby określić, czy łańcuch może być parsowany do liczby całkowitej.
int i;
bool bNum = int.TryParse(str, out i);
Logiczny powie Ci, czy zadziałało, czy nie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-21 18:10:24
Jeśli chcesz wiedzieć, czy łańcuch jest liczbą, zawsze możesz spróbować ją przetworzyć:
var numberString = "123";
int number;
int.TryParse(numberString , out number);
Zauważ, że TryParse
zwraca bool
, którego możesz użyć, aby sprawdzić, czy Twoje parsowanie się powiodło.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-21 18:11:02
Aktualizacja odpowiedzi Kunal Noel
stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.
Ale w tym przypadku mamy, że puste ciągi zdadzą ten test, więc możesz:
if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
// Do your logic here
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-18 17:55:44
Jeśli chcesz sprawdzić, czy łańcuch jest liczbą(zakładam, że jest łańcuchem, ponieważ jeśli jest liczbą, wiesz, że jest jedną).
- bez regex i
- używanie kodu Microsoftu w jak największym stopniu
Można też zrobić:
public static bool IsNumber(this string aNumber)
{
BigInteger temp_big_int;
var is_number = BigInteger.TryParse(aNumber, out temp_big_int);
return is_number;
}
To zajmie się zwykłymi paskudami:
- Minus ( - ) lub Plus ( + ) na początku
-
zawiera znak dziesiętnyBigintegery nie będą analizować liczb z punktami dziesiętnymi. (So:BigInteger.Parse("3.3")
rzuci wyjątek iTryParse
dla tego samego zwróci false) - brak śmiesznych cyfr
- obejmuje przypadki, w których liczba jest większa niż zwykłe użycie
Double.TryParse
Będziesz musiał dodać odniesienie do System.Numerics
i mieć
using System.Numerics;
na szczycie swojej klasy (cóż, drugi to chyba bonus:)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-13 18:06:48
Myślę, że ta odpowiedź zostanie utracona pomiędzy wszystkimi innymi, ale tak czy siak, zaczyna się.
Trafiłem na to pytanie przez Google, ponieważ chciałem sprawdzić, czy string
jest numeric
, aby móc po prostu użyć double.Parse("123")
zamiast metody TryParse()
.
out
i sprawdzanie wyniku TryParse()
, zanim dowiesz się, czy parse nie powiodło się, czy nie. Chcę użyć ternary operator
, aby sprawdzić, czy string
jest numerical
, a następnie po prostu przetworzyć go w pierwsze wyrażenie trójskładnikowe lub podaj wartość domyślną w drugim wyrażeniu trójskładnikowym.
Tak:
var doubleValue = IsNumeric(numberAsString) ? double.Parse(numberAsString) : 0;
Jest po prostu dużo czystsze niż:
var doubleValue = 0;
if (double.TryParse(numberAsString, out doubleValue)) {
//whatever you want to do with doubleValue
}
Zrobiłem kilka extension methods
dla tych przypadków:
Extension method one
public static bool IsParseableAs<TInput>(this string value) {
var type = typeof(TInput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return false;
var arguments = new[] { value, Activator.CreateInstance(type) };
return (bool) tryParseMethod.Invoke(null, arguments);
}
Przykład:
"123".IsParseableAs<double>() ? double.Parse(sNumber) : 0;
Ponieważ IsParseableAs()
próbuje przetworzyć łańcuch jako odpowiedni typ, zamiast sprawdzać, czy łańcuch jest "numeryczny", powinien być całkiem bezpieczny. I możesz nawet użyj go dla typów nieliczbowych, które mają metodę TryParse()
, Jak DateTime
.
Metoda wykorzystuje reflection i kończy się wywołaniem metody TryParse()
dwa razy, co oczywiście nie jest tak efektywne, ale nie wszystko musi być w pełni zoptymalizowane, czasami wygoda jest po prostu ważniejsza.
Ta metoda może być również używana do łatwego przetworzenia listy ciągów liczbowych do listy double
lub innego typu z wartością domyślną bez konieczności wyłapywania żadnych wyjątki:
var sNumbers = new[] {"10", "20", "30"};
var dValues = sNumbers.Select(s => s.IsParseableAs<double>() ? double.Parse(s) : 0);
Extension method two
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue) {
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder,
new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool) tryParseMethod.Invoke(null, arguments)) ? (TOutput) arguments[1] : defaultValue;
}
Ta metoda rozszerzenia pozwala przetworzyć string
jako dowolną type
, która ma metodę TryParse()
, a także pozwala określić domyślną wartość, która ma zostać zwrócona, jeśli konwersja się nie powiedzie.
Jest to lepsze niż użycie operatora trójdzielnego z powyższą metodą rozszerzenia, ponieważ konwersja odbywa się tylko raz. Jednak nadal używa refleksji...
Przykłady:
"123".ParseAs<int>(10);
"abc".ParseAs<int>(25);
"123,78".ParseAs<double>(10);
"abc".ParseAs<double>(107.4);
"2014-10-28".ParseAs<DateTime>(DateTime.MinValue);
"monday".ParseAs<DateTime>(DateTime.MinValue);
Wyjścia:
123
25
123,78
107,4
28.10.2014 00:00:00
01.01.0001 00:00:00
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-07 23:12:04
bool Double.TryParse(string s, out double result)
Najlepsze elastyczne rozwiązanie z wbudowaną funkcją. NET o nazwie - char.IsDigit
. Działa z nieograniczonymi długimi numerami. Zwróci true tylko wtedy, gdy każdy znak jest liczbą liczbową. Używałem go wiele razy bez żadnych problemów i o wiele łatwiejszego do czyszczenia rozwiązania, jakie kiedykolwiek znalazłem. Zrobiłem przykładową metodę.Jest gotowy do użycia. Dodatkowo dodałem walidację dla null i empty input. Tak więc metoda jest teraz całkowicie kuloodporna
public static bool IsNumeric(string strNumber)
{
if (string.IsNullOrEmpty(strNumber))
{
return false;
}
else
{
int numberOfChar = strNumber.Count();
if (numberOfChar > 0)
{
bool r = strNumber.All(char.IsDigit);
return r;
}
else
{
return false;
}
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-12-08 03:35:36
W c # 7 można wstawić zmienną out:
if(int.TryParse(str, out int v))
{
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-09 23:39:38
Użyj tych metod rozszerzenia, aby wyraźnie rozróżnić, czy łańcuch jest numeryczny, a jeśli łańcuch tylko zawiera 0-9 cyfr
public static class ExtensionMethods
{
/// <summary>
/// Returns true if string could represent a valid number, including decimals and local culture symbols
/// </summary>
public static bool IsNumeric(this string s)
{
decimal d;
return decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out d);
}
/// <summary>
/// Returns true only if string is wholy comprised of numerical digits
/// </summary>
public static bool IsNumbersOnly(this string s)
{
if (s == null || s == string.Empty)
return false;
foreach (char c in s)
{
if (c < '0' || c > '9') // Avoid using .IsDigit or .IsNumeric as they will return true for other characters
return false;
}
return true;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-03 09:59:20
public static bool IsNumeric(this string input)
{
int n;
if (!string.IsNullOrEmpty(input)) //.Replace('.',null).Replace(',',null)
{
foreach (var i in input)
{
if (!int.TryParse(i.ToString(), out n))
{
return false;
}
}
return true;
}
return false;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-13 07:25:06
Spróbuj reges poniżej
new Regex(@"^\d{4}").IsMatch("6") // false
new Regex(@"^\d{4}").IsMatch("68ab") // false
new Regex(@"^\d{4}").IsMatch("1111abcdefg")
new Regex(@"^\d+").IsMatch("6") // true (any length but at least one digit)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-16 11:32:18
Hope this helps
string myString = "abc";
double num;
bool isNumber = double.TryParse(myString , out num);
if isNumber
{
//string is number
}
else
{
//string is not a number
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-02 11:32:29
Pobierz odniesienie do Visual Basic w swoim projekcie i wykorzystaj jego informacje.Metoda IsNumeric, taka jak pokazana poniżej i być w stanie uchwycić pływaki, jak również liczby całkowite w przeciwieństwie do odpowiedzi powyżej, która łapie tylko int.
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-17 21:14:06
Wszystkie odpowiedzi są przydatne. Ale podczas wyszukiwania rozwiązania, gdzie wartość liczbowa jest 12 cyfr lub więcej (w moim przypadku), a następnie podczas debugowania, znalazłem następujące rozwiązanie przydatne :
double tempInt = 0;
bool result = double.TryParse("Your_12_Digit_Or_more_StringValue", out tempInt);
Ta zmienna wyniku da ci wartość true lub false.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-23 11:39:05
Oto metoda C#. Int.Metoda TryParse (String, Int32)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-21 19:01:03
//To my knowledge I did this in a simple way
static void Main(string[] args)
{
string a, b;
int f1, f2, x, y;
Console.WriteLine("Enter two inputs");
a = Convert.ToString(Console.ReadLine());
b = Console.ReadLine();
f1 = find(a);
f2 = find(b);
if (f1 == 0 && f2 == 0)
{
x = Convert.ToInt32(a);
y = Convert.ToInt32(b);
Console.WriteLine("Two inputs r number \n so that addition of these text box is= " + (x + y).ToString());
}
else
Console.WriteLine("One or two inputs r string \n so that concatenation of these text box is = " + (a + b));
Console.ReadKey();
}
static int find(string s)
{
string s1 = "";
int f;
for (int i = 0; i < s.Length; i++)
for (int j = 0; j <= 9; j++)
{
string c = j.ToString();
if (c[0] == s[i])
{
s1 += c[0];
}
}
if (s == s1)
f = 0;
else
f = 1;
return f;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-13 18:03:04