I want the program to get all of the elem1-elem7 info, add it together, and put it into the totalElem variable. That part works fine.
The part I'm stuck on, is that I want to take that number (lets say 30 for example), and put it on the end of a decimal to use it as a multiplier. Therefore 30 would become 1.30.
The error I'm getting is:
Cannot implicitly convert type 'string' to 'decimal'.
Please note, that is not where the variable definitions really are in the code. I just put them there so I didn't have to post my whole program.
private void calculateButton_Click(object sender, EventArgs e)
{
int startingSheetDPS;
int chd;
int skill;
int elem7;
int elem6;
int elem5;
int elem4;
int elem3;
int elem2;
int elem1;
int totalElem;
decimal elemMultiplier;
decimal baseMultiplier;
elem1 = Convert.ToInt32(ele1.Text);
elem2 = Convert.ToInt32(ele2.Text);
elem3 = Convert.ToInt32(ele3.Text);
elem4 = Convert.ToInt32(ele4.Text);
elem5 = Convert.ToInt32(ele5.Text);
elem6 = Convert.ToInt32(ele6.Text);
elem7 = Convert.ToInt32(ele7.Text);
chd = Convert.ToInt32(chd1.Text);
skill = Convert.ToInt32(skill1.Text);
totalElem = elem1 + elem2 + elem3 + elem4 + elem5 + elem6 + elem7;
elemMultiplier = 1 + "." + totalElem;
}
In short, I want to be able to turn elemMultiplier into a decimal variable, containing 1.totalElem.
Ok, a really dirty and fast way, replace your
elemMultiplier = 1 + "." + totalElem;
with
elemMultiplier = decimal.Parse("1." + totalElem);
Be ware, this is locale-dependant.
Use this:
String elemMul = "1." + totalElem.ToString();
elemMultiplier = Convert.ToDecimal(elemMul);
Your code shows problem because "." is a string which cannot be converted to decimal implicitly.
Don't concatenate strings. Just do the math:
elemMultiplier =
Convert.ToDecimal(1 + (totalElem / Math.Pow(10, totalElem.ToString().Length)));
(Edited after Gusman noticed a problem.)
Related
I have one simple windows application in that amount Textbox is there. When i enter amount into amount textbox it will convert it to words in another textbox named txtrupees. Amount Textbox field maximum length is set to 11 places in that last 3 places .00.
My problem is now when i Enter amount with .00 it is working fine. But if i enter 11 places it will giving following Error:
System.OverflowException' occurred in mscorlib.dll Value was either too large or too small for an Int32.tried following code.
How can I prevent this kind of error?
private void txtamount_TextChanged(object sender, EventArgs e)
{
if (txtamount.Text != string.Empty)
{
string[] amount = txtamount.Text.Split('.');
if (amount.Length == 2)
{
int rs, ps;
int.TryParse(amount[0], out rs);
int.TryParse(amount[1], out ps);
string rupees = words(rs);
string paises = words(ps);
txtrupees.Text = rupees + " rupees and " + paises + " paisa only ";
}
else if (amount.Length == 1)
{
string rupees = words(Convert.ToInt32(amount[0]));
txtrupees.Text = rupees + " rupees only";
}
}
}
The issue comes from Convert.ToInt32(amount[0]) where amount[0] can be almost anything, including being superior to Int.MaxValue or inferior to Int.MinValue which would cause an overflow.
Use int.TryParse(amount[0], out foo); and use foo:
else if (amount.Length == 1)
{
int ps;
if(int.TryParse(amount[0], out ps))
{
string rupees = words(ps);
txtrupees.Text = rupees + " rupees only";
}
else
txtrupees.Text = "Invalid number";
}
If you want to deal with bigger numbers, you can use Int64, Double or Decimal
a number that has 11 places is larger than a Int32 number. I suggest you should use int64 instead of int32
https://msdn.microsoft.com/en-us/library/29dh1w7z.aspx
private void txtFinal_Leave_1(object sender, EventArgs e)
{
int prelim;
int midterm;
int final;
decimal average;
string remarks;
prelim = int.Parse(txtPrelim.Text);
midterm = int.Parse(txtMidterm.Text);
final = int.Parse(txtFinal.Text);
average = (prelim + midterm + final) / 3;
txtAverage.Text = average.ToString();
if (average >= 75)
{
remarks = "passed";
}
else
{
remarks = "failed";
}
txtRemarks.Text = remarks;
// this is the output 83 passed
// I want to be like this 83.25 passed
}
average = (prelim + midterm + final) / 3.0m;
This will fix your problem.
Int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: 3.0m this is casting to decimal !
please upgrade your code as follow:
average = Convert.ToDecimal(prelim + midterm + final) / 3;
txtAverage.Text = string.Format("{0:0.00}", average);
how can i get string between two dots for example ?
[Person.Position.Name]
for this case I want to get the string "Position"
I can also have three dots ….
[Person.Location.City.Name]
I want to take all strings between dots
I know it's a year old question, but the other answers are not sufficient, like they are even pretending that you want "Location.City" because they don't know how to seperate them.. The solution is simple though, don't use indexof.
say you want to seperate the Four (not 3) parts:
String input = "Person.Location.City.Name"
string person = input.Split('.')[0];
string location = input.Split('.')[1];
string city = input.Split('.')[2];
string name = input.Split('.')[3];
Console.WriteLine("Person: " + person + "\nLocation: " + location + "\nCity: " + city + "\nName: " + name);
This might help you:
string s = "Person.Position.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
string result = s.Substring(start, end - start);
It will return all the values between the first and the last dot.
If you don't want the result with dot between the strings, you can try this:
string s = "Person.Location.Name";
int start = s.IndexOf(".") + 1;
int end = s.LastIndexOf(".");
var result = s.Substring(start, end - start).Split('.');
foreach (var item in result)
{
//item is some string between the first and the last dot.
//in this case "Location"
}
Try this
string str = "[Person.Location.City.Name]";
int dotFirstIndex = str.IndexOf('.');
int dotLastIndex = str.LastIndexOf('.');
string result = str.Substring((dotFirstIndex + 1), (dotLastIndex - dotFirstIndex) - 1); // output Location.City
I noticed that the fully qualified name of an object I had written was coming back funny. While stepping through my ToString() method, I noticed that when it came to concatenating the string, a character object was consistently being left out of that process.
Here's a step through of what's happening
Before
After
Where Char seperator = ':';
Here's the code of my tostring function:
public String ToString(Representaion rep)
{
String toReturn = "kuid";
Char separator = ':';
switch (rep)
{
case Representaion.Colons:
break;
case Representaion.Underscores:
separator = '_';
break;
case Representaion.UCROnly:
toReturn = userID + ":" + contentID;
toReturn += revision == 0 ? "" : ":" + revision;
return toReturn;
}
toReturn += version == 0 ? "" : version.ToString();
toReturn += separator + userID + separator + contentID;
toReturn += revision == 0 ? "" : separator + revision.ToString();
return toReturn;
}
Where you have
private byte version;
private int userID;
private int contentID;
private byte revision;
And one case may look like this:
Already, looking in the locals panel, it seems like VS is getting a string other than what I think it would.
I put in another ToString function to handle a call without parameters (which it does by calling the parametrized function with Representation.Colons):
public override string ToString()
{
return this.ToString(KUID.Representaion.Colons);
}
Can anyone tell why I'm not getting what I think I should be getting? (Expected result: kuid2:72938:40175:2)
Now that you've posted more of your program the problem is obvious. Char plus int is not string. Remember,
string += char + int + char + int
means:
string = string + (((char + int ) + char) + int)
And when you add an int to a char, you get an int: 'a' + 2 produces the integer character code corresponding to 'c', not the string "a2".
You're getting some crazy integer by adding the user id to the colon char.
Concatenating strings like this is a bad practice for exactly the reason you have run into. Instead, say:
return string.Format("kuid{0}{1}{2}{3}{4}{5}{6}",
version, separator, userID, separator, contentID,
revision == 0 ? "" : separator.ToString(),
revision == 0 ? "" : revision.ToString());
Or, even better, use a StringBuilder object to build a complicated string.
Incidentally, this illustrates an interesting point about the language:
a += b + c;
does not mean
a = (a + b) + c;
It means
a = a + (b + c);
which as we've seen, might have a different type analysis! Had you said:
string = string + char + int + char + int
then that would have been analyzed as
string = ((((string + char) + int) + char ) + int;
Which does make everything a string.
I copy pasted your code and it works fine
The problem happens, because the expression to the right is not a string expression. You are working with characters and integers which are not automatically converted to a string, unless they are used within a string expression. You can make it a string expression by starting with a string (here an empty string):
toReturn += "" + separator + userID + separator + contentID;
i have a numerical textbox which I need to add it's value to another number
I have tried this code
String add = (mytextbox.Text + 2)
but it add the number two as another character like if the value of my text box is 13 the result will become 132
The type of mytextbox.Text is string. You need to parse it as a number in order to perform integer arithmetic, e.g.
int parsed = int.Parse(mytextbox.Text);
int result = parsed + 2;
string add = result.ToString(); // If you really need to...
Note that you may wish to use int.TryParse in order to handle the situation where the contents of the text box is not an integer, without having to catch an exception. For example:
int parsed;
if (int.TryParse(mytextbox.Text, out parsed))
{
int result = parsed + 2;
string add = result.ToString();
// Use add here
}
else
{
// Indicate failure to the user; prompt them to enter an integer.
}
String add = (Convert.ToInt32(mytextbox.Text) + 2).ToString();
You need to convert the text to an integer to do the calculation.
const int addend = 2;
string myTextBoxText = mytextbox.Text;
var doubleArray = new double[myTextBoxText.ToCharArray().Length];
for (int index = 0; index < myTextBoxText.ToCharArray().Length; index++)
{
doubleArray[index] =
Char.GetNumericValue(myTextBoxText.ToCharArray()[index])
* (Math.Pow(10, (myTextBoxText.ToCharArray().Length - 1) - index));
}
string add =
(doubleArray.Aggregate((term1, term2) => term1 + term2) + addend).ToString();
string add=(int.Parse(mytextbox.Text) + 2).ToString()
if you want to make sure the conversion doesn't throw any exception
int textValue = 0;
int.TryParse(TextBox.text, out textValue);
String add = (textValue + 2).ToString();
int intValue = 0;
if(int.TryParse(mytextbox.Text, out intValue))
{
String add = (intValue + 2).ToString();
}
I prefer TryPase, then you know the fallback is going to be zero (or whatever you have defined as the default for intValue)
You can use the int.Parse method to parse the text content into an integer:
String add = (int.Parse(mytextbox.Text) + 2).ToString();
Others have posted the most common answers, but just to give you an alternative, you could use a property to retrieve the integer value of the TextBox.
This might be a good approach if you need to reuse the integer several times:
private int MyTextBoxInt
{
get
{
return Int32.Parse(mytextbox.Text);
}
}
And then you can use the property like this:
int result = this.MyTextBoxInt + 2;