Example -
textbox.Text = "456/789";
var nominator = 456;
var denominator = 789
How could I code this in c# ?
Also, how could I make one number from elements of array. For example, {1,5,7,6} would become 1576.
And now, i have such bad idea, but i wont to know: if I have int number in nominator, I will do one method from my1.cs, if I have double number in nominator/denominator I will do method from another class called my2.cs . How I may code IF, if (number = int;bla bla bla...), if (number = double; bla bla bla...)
string[] input = textbox.Text.Split('/');
var nominator = input[0];
var denominator = input[1];
Assuming you will always have the input in that format.
String.Join will smash them back together for you. Just don't use a separator.
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
1)
var value = textbox.Text.Split('/');
var nominator = value[0];
var denominator = value[1];
2)
String.Join
For the numerator and denominator, you could use "substring" or "split" to split/select the numbers before and after the "/".
For the array, you could loop through it, and add each number to a string, then convert that string to an integer.
Hope this helps!
Something like:
1.
string[] numdenom = textbox.Text.Split('/');
var numerator = numdenom[0];
var denominator = numdenom[1];
2.
string[] digits = new string[] { "1","5","7","6" };
string number = string.Join(string.Empty, digits);
int numberValue = int.Parse(number); // or int.TryParse if you prefer
For the first question, splitting the nominator and denominator I would use simple substring methods:
textbox.Text.substring(0, textbox.text.indexof("\"); //denominator
textbox.text.substring(textbox.text.indexof("\") + 1); //numerator
For the second, I'd suggest using a foreach loop to loop through each item in the array and concatenate onto a string object. I say a string object so you don't end up adding the numbers together, getting 19 instead of 1576.
This should work for the numerator and denominator.
var parts = textbox.Text.Split('/');
var numerator = parts[0];
var denominator = parts[1];
As for combining the elements of an array, you'll need to convert and build up a string, then convert it back to a number.
var numbers = new[] {1, 5, 7, 6};
var builder = new StringBuilder();
for each (var i in numbers) {
builder.Append(i);
}
var result = int.Parse(builder.ToString());
Related
How to convert -5.55111512312578E-17 to 5.55?
my code:
var value=reader11["PendingQty"].ToString().Replace('-', ' ');
var a=String.Format("{0:0.00}", value);
i also Tried : value= Math.round
-5.55111512312578E-17 is equal to 0.0000000000000000555111512312578. You could get this value by doing this:
double output = Double.Parse(input, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(output.ToString("F99").TrimEnd('0'));
But as far as I understood, you actually only want to first three digits, so I would do a string manipulation:
input.Substring(1,4);
This takes 4 characters, starting at the second position. If you have positive values too, simply check and read from the first digit on:
var res = "";
if (input.StartsWith("-")) {
res = input.Substring(1,4));
}
else {
res = input.Substring(0,4);
}
I copy manually form excel to string collection (ComboBox) 2 columns, 1 is account (456939493) number the second is the percent(0.001) in decimals.
this.percent.Items.AddRange(new object[] {
"456939493 0.001 ",
"453949343 0.00001",
operation
double Pairdecimal = Convert.ToDouble(percent.SelectedValue);
When the multiplication operation is executed it does not read the decimals, and only generated the number zero.
What can do to get only the decimal and not the account number from the string collection (ComboBox).
You can split string and then convert first part to int. Like this:
var splitStrings = percent.SelectedValue.Split();
var firstValue = Convert.ToInt32(splitStrings[0]); //int
var secondValue = Convert.ToDouble(splitStrings[1]); //double
There are many ways to do this, and swistak has provided one good answer.
You need to separate the string into its component parts first, and then convert the desired part to a double (or decimal).
string text = "456939493 0.001 ";
//one option
string[] textArray = text.Split(' ');
double num1 = Convert.ToDouble( textArray[1]);
//another option
double num2 = Convert.ToDouble(text.Substring(10));
// this assumes the account number is always the same length
Thanks for the answers!
I took both suggestions/answers and made it work for my code.
string[] str = currpair.Text.Split(); //from Ric Gaudet
Then I also took
double secondValue = Convert.ToDouble(str[1]); //from swistak
Thanks again my problem is solved.
Now I can multiply the comboBox value.
I have string like this:
strings s = "1.0E-20"
Is there a way to get only -20 from this using regex?
I tried this:
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE][-+]?[0-9]+)?
this gets me e-20 in group5 but still not just -20.
Use Regex for dealing with text, use Math(s) for dealing with numbers:
Math.Log10(Convert.ToDouble("1.0E-20")) // returns -20
To make sure your string input is a valid double use TryParse:
double d, result = 0.0;
if (Double.TryParse("1.0E-20", out d))
{
result = Math.Log10(d);
}
else
{
// handle error
}
Also, if you want to get the 1.0 (multiplier) from your input:
var d = Convert.ToDouble("1.0E-20");
var exponent = Math.Log10(d);
var multiplier = d / exponent;
No need for Regex when string methods can do wonders
string str = "1.0E-20";
str = str.Substring(str.IndexOf('E') + 1);
You can do that without Regex like:
string s = "1.0E-20";
string newStr = s.Substring(s.IndexOf('E') + 1);
Later you can parse the string to number like:
int number;
if (!int.TryParse(newStr, out number))
{
//invalid number
}
Console.WriteLine(number);
You can also use string.Split like:
string numberString = s.Split('E')[1]; //gives "-20"
Its better if you add check for string/array length when access string.Substring or accessing element 1 after split.
var x = str.IndexOf("E") != -1 ? str.Substring(str.IndexOf("E") + 1) : "1";
If you want to use regular expressions to achieve this, you should switch up your capture groups.
(([1-9]+\.[0-9]*)|([1-9]*\.[0-9]+)|([1-9]+))([eE])([-+]?[0-9]+)?
Group 6 will contain -20 with your given example with the regular expression above. Note how the parentheses have moved. We might need more information from you though. Do you have any more sample data? What's the end goal here?
I would like to parse a string to return only a value that is in between bracket symbols, such as [10.2%]. Then I would need to strip the "%" symbol and convert the decimal to a rounded up/down integer. So, [10.2%] would end up being 10. And, [11.8%] would end up being 12.
Hopefully I have provided sufficient information.
Math.Round(
double.Parse(
"[11.8%]".Split(new [] {"[", "]", "%"},
StringSplitOptions.RemoveEmptyEntries)[0]))
Why not use Regex?
In this example, I am assuming that your value inside the brackets always are a double with decimals.
string WithBrackets = "[11.8%]";
string AsDouble = Regex.Match(WithBrackets, "\d{1,9}\.\d{1,9}").value;
int Out = Math.Round(Convert.ToDouble(AsDouble.replace(".", ","));
var s = "[10.2%]";
var numberString = s.Split(new char[] {'[',']','%'},StringSplitOptions.RemoveEmptyEntries).First();
var number = Math.Round(Covnert.ToDouble(numberString));
If you can ensure that the content between the brackets is of the form <decimal>%, then this little function will return the value between the fist set of brackets. If there are more than one values you need to extract then you will need to modify it somewhat.
public decimal getProp(string str)
{
int obIndex = str.IndexOf("["); // get the index of the open bracket
int cbIndex = str.IndexOf("]"); // get the index of the close bracket
decimal d = decimal.Parse(str.Substring(obIndex + 1, cbIndex - obIndex - 2)); // this extracts the numerical part and converts it to a decimal (assumes a % before the ])
return Math.Round(d); // return the number rounded to the nearest integer
}
For example getProp("I like cookies [66.7%]") gives the Decimal number 67
Use regular expressions (Regex) to find the required words within one bracket.
This is the code you need:
Use an foreach loop to remove the % and convert to int.
List<int> myValues = new List<int>();
foreach(string s in Regex.Match(MYTEXT, #"\[(?<tag>[^\]]*)\]")){
s = s.TrimEnd('%');
myValues.Add(Math.Round(Convert.ToDouble(s)));
}
I have strings that look like this:
1. abc
2. def
88. ghi
I'd like to be able to get the numbers from the strings and put it into a variable and then get the remainder of the string and put it into another variable. The number is always at the start of the string and there is a period following the number. Is there an easy way that I can parse the one string into a number and a string?
May not be the best way, but, split by the ". " (thank you Kirk)
everything afterwards is a string, and everything before will be a number.
You can call IndexOf and Substring:
int dot = str.IndexOf(".");
int num = int.Parse(str.Remove(dot).Trim());
string rest = str.Substring(dot).Trim();
var input = "1. abc";
var match = Regex.Match(input, #"(?<Number>\d+)\. (?<Text>.*)");
var number = int.Parse(match.Groups["Number"].Value);
var text = match.Groups["Text"].Value;
This should work:
public void Parse(string input)
{
string[] parts = input.Split('.');
int number = int.Parse(parts[0]); // convert the number to int
string str = parts[1].Trim(); // remove extra whitespace around the remaining string
}
The first line will split the string into an array of strings where the first element will be the number and the second will be the remainder of the string.
Then you can convert the number into an integer with int.Parse.
public Tuple<int, string> SplitItem(string item)
{
var parts = item.Split(new[] { '.' });
return Tuple.Create(int.Parse(parts[0]), parts[1].Trim());
}
var tokens = SplitItem("1. abc");
int number = tokens.Item1; // 1
string str = tokens.Item2; // "abc"