C# Combo Box items number multiplication - c#

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.

Related

How to +/add text together to get total C#

I have basically two text which I would like to plus together to get a total.
What I need this to do is :
price.Text = 50.50
addprice.Text = 140.50
price.Text + addprice.Text
to get : 191.00
I tried looking everywhere to find how to get this working, Any ideas/suggestions. Much Appreciated.
You cannot perform mathematical operations on strings directly, you need to use a numeric data type for that.
Let's do this step by step:
Convert your texts to numbers. You can use Decimal.TryParse for that. Think about what you want to happen if the text does not contain a valid number.
Add your numbers.
Convert your sum back to text. You can use Decimal.ToString for that.
Implementation is left as an exercise, but the SO crowd will surely help you if you get stuck.
Note: Since your numbers seem to be monetary values, you should use decimal rather than double or float).
var total = Convert.ToDecimal(price.Text) + Convert.ToDecimal(addPrice.Text);
Convert your strings to decimal then sum and if you want to convert back to string just: total.ToString()
As string:
string total = (decimal.Parse(price.Text) + decimal.Parse(addPrice.Text)).ToString();
or as decimal:
decimal total = decimal.Parse(price.Text) + decimal.Parse(addPrice.Text);
You need to parse those texts into a numbers (floats in this case).
float priceNumber = 0;
float addPriceNumber = 0;
if(float.TryParse(price.Text, out priceNumber) && float.TryParse(addprice.Text, out addPriceNumber )) {
//Here, the priceNumber and addPriceNumber has numbers stored as float
float result = priceNumber + addPriceNumber;
} else {
//Error parsing, wrong format of numbers
}
Docs: float.TryParse / Single.TryParse
Some knowledge about parsing: Wiki

Read out one Line for two variables but one is double and the other one is a string

I wanted to read out two variables from one line, so I used var.
I encountered some difficulties with the second variable beeing a double and the first one beeing a string.
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = Convert.ToDouble(inputParts[1]);
What's wrong with this type of code? Visual Studio didn't help me out there.
Thank you in forward :)
temp1 = double.Parse(inputParts[1]);
I guess that temp0 and temp1 do not have the right type. For that code to work they should be defined as:
string temp0;
double temp1;
Edit: based on your comment below what you're actually getting is a run time exception because the string you're trying to parse does not match the expected format of a double.
You could print inputParts[1] to check what it actually contains.
If you're expecting your double to look like 1.0 (with a . for decimal separator) then you should do
temp1 = float.Parse(inputParts[1],CultureInfo.InvariantCulture);
If you don't use CultureInfo.InvariantCulture then the way that the double is parsed will depend on the user's locale. The locale might be such that it expects a comma to be the decimal separator e.g. "1,0" so when it sees a '.' it will throw an exception.
Note that you will need to add
using System.Globalization;
Here is a complete program that works:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
string temp0;
double temp1;
var inputParts = Console.ReadLine().Split(' ');
temp0 = inputParts[0];
temp1 = double.Parse(inputParts[1], CultureInfo.InvariantCulture);
Console.WriteLine(string.Format("The double was parsed as {0}", temp1));
}
}
If you run this and enter input like
firstPartThatIsIgnored 100.5
You will get output
The double was parsed as 100.5
What language are you using? Presuming you're splitting based on a Space, I'd parse it as a String array. Check and see the type of the part first, before trying to convert to avoid exceptions.
string input = "x 3.3 z 2";
string[] cars = input.split(" ");
double x = double.TryParse(cars[1]);
If you are trying to just extract a double from a random string of input, you could use something like this:
string inputData = "sfdsdf2.2222sfdsfs";
var data = Regex.Match(inputData, "^(-?)(0|([1-9][0-9]*))(\\.[0-9]+)?$").Value;

How to change the 3 in {0:f3} to an int from user input

Solved, thanks for the help!
So I got an assignment for school, and no matter how much I search the net or read my books I can't figure out the answer to the question.
I have done programming for about 4 hours, so thats why the question is phrased wierdly, I think.
Console.WriteLine("Enter a number with any number of decimals.");
string input;
input = Console.ReadLine();
decimal myNumber = decimal.Parse(input);
Console.WriteLine("Please specify how many decimals you want to be shown.");
string input2;
input22 = Console.ReadLine();
int myDecimal = int.Parse(input2);
Console.WriteLine(("Your number with the choosen number of decimals: {0:f3}"), myNumber);
So, when I run it and enter 2,1234567 as my number and 5 as my number of decimals, it prints 2,123 instead of 2,12345.
I know it prints 3 decimals because of the 3 after the f, but I can't figure out how to change the 3 into the ammount chosen by the user.
I have tried {0:f(myDecimal)}, {myDecimal:f and {0:f(int = myDecimal)} , none of which I expected to work as I was just testing things out.
The answer is probably really simple, and I'm probably just overthinking things, but help would be very much appriciated!
You need a format-ception here:
// the {{ and }} escapes to { and }
var numberFormat = string.Format("{{0:f{0}}}", myDecimal).Dump();
Console.WriteLine("Your number with the choosen number of decimals: " + numberFormat, myNumber);
You can use ToString too
decimal myNumber = 224323.545656M;
int myDecimal = 4;
Console.WriteLine(String.Format("Your number with the choosen number of decimals: {0} " , myNumber.ToString("F" + myDecimal)));
You could just simply change your last Console.WriteLine() call to this:
Console.WriteLine("Your number with the choosen number of decimals: {0}",
myNumber.ToString("f" + input2));
The part that changes is: myNumber.ToString("f" + input2). What this does is use string concatenation to build your format string from your variable input2.
I made a fiddle here.
Please keep in mind though, the format string you are using ("F") will round to that number of decimal places (i.e 1.236 would become 1.24 with format "F2")
You need to build the format string dynamically. At this point using a substituted string is harder than ToString:
var digits = 3;
var input = 2.123456789;
var format = $"F{digits}";
var output = "Some text {input.ToString(format)} some more text";

Parse string and return only the information between bracket symbols. C# Winforms

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)));
}

How to select nominator and denominator from textbox in c#?

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());

Categories