I am trying to get only part with number. For example in input could be just number like 50, or string like: 50 and more. Also Number always will be on first place. And I want always to get only number from that. I tried like this, but this does not work:
double presureTendency;
var presureTendencyToString= Convert.ToString(presureTendency.ToString());
var presureTendencySplited = presureTendencyToString.Split(' ');
var pressureTendencyNumber = presureTendencySplited[0];
CodePudding user response:
You can extract the number from the string using a regular expression. See an example below. One thing to pay an attention to are your locale settings as they influence the format of the double.
string pattern = @"^\d \.\d ";
string input = "50.1 , or more";
Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
if (m.Success) {
double nr = Double.Parse(m.Value);
Console.WriteLine(nr);
}
CodePudding user response:
So if i enter "507.89foo123,456bah" you want only 507 or you want 507.89? –
Please read, I write 50, not 50 with coma or something decimal. I just want 507 in your example
Well, then it's pretty easy:
string input = "50.1 , or more";
char[] digits = input.TakeWhile(Char.IsDigit).ToArray();
if(digits.Any())
{
string result = new string(digits); // "50"
// if you want an integer:
int number = int.Parse(result);
}
CodePudding user response:
If only want the number at the beginning of the string you can do it by simply parsing the initial value and ignoring the rest, since, judging from your comments, you don't have decimal separators it's even simpler:
var myString = Console.ReadLine().Trim(' '); // read console input
// trim spaces
var numericString = new List<char>();
foreach (var c in myString)
{
if (char.IsDigit(c))
{
numericString.Add(c); // if is digit parse
}
else
{
break; // the first non digit breaks the cycle
}
}
// parse the value as int
if (int.TryParse(numericString.ToArray(), out var myVal))
{
Console.WriteLine(myVal);
}
