I'd like to convert a string to a double. I know, it has been asked before, but let me finish it! :)
So I read the string in from a USB port (Arduino experiment), and I'd like to add that value to a list of doubles. The values are coming in continuously.
The problem is, when I try to convert the string to double it gives an error message that says: "The format of the incoming character chain is wrong" or something like this. I get this error message with both the parse and convert command.
What should I do?
Here's the part of the code that supposed to do the job:
namespace voltmeres{
public partial class Form1 : Form
{
List<double> lista = new List<double>();
int i;
double f;
string POT;
public Form1()
{
InitializeComponent();
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
lista.Capacity = 100;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT =serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
From the comments, it looks like it's a number formatting issue. Try the following:
f = Convert.ToDouble(textBox1.Text, new System.Globalization.CultureInfo("en-US"));
Try this
private void timer1_Tick(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
POT = serialPort1.ReadExisting();
textBox1.Text = POT.ToString();
}
if (! double.TryParse(textBox1.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out f)) return;
f = Convert.ToDouble(textBox1.Text);
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity = lista.Capacity + 100;
}
}
You should use double.TryParse instead. It will parse if it is a double, else it will not throw an exception.
if(double.TryParse(textBox1.Text,outf))
{
lista.Add(f);
i++;
if (i == lista.Capacity)
{
lista.Capacity=lista.Capacity + 100;
}
}
If the above answers don't work, try 'String.valueOf(your double);' This should do the trick if your double is correct.
Another suggestion : depending on the double you have, for instance if it is a really long double, you may want to format the value before or after the conversion to take only a few digits.
Related
I am beginner , am trying to create a calculator. the way of the code working is there is a method for summing and one for subtraction ETC.
when i call the subtraction method unwanted minus appears before the answer in the textbox ( i know my code could be using harder way to do the same purpose but i am just beginner trying to do some code )
double rat;
byte operations;
public void TheEqualMinus(double earlier) //Substraction Operation Method
{
double _minus;
_minus = Convert.ToDouble(result.Text);
double last = _minus - earlier;
result.Text = last.ToString();
}
private void button15_Click(object sender, EventArgs e)
{
//The Subtract Button
operations = 2;
rat = Convert.ToDouble(result.Text);
label1.Text = rat + " -";
result.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
// equal button
NewText = true; //boolean to newtext
switch (operations)
{
case (1): //addition
TheEqualSum(rat);
label1.Text = "";
break;
case (2): //substraction
TheEqualMinus(rat);
label1.Text = "";
break;
}
}
and the answer output becomes " - The Correct Answer i want "
ex. 9-6 = -3
so any ideas how to remove this minus ?
As per the comments above, this was fixed by simply changing this:
double last = _minus - earlier;
to this:
double last = earlier - _minus;
I am making a c-sharp application that converts the distance units.
My application prompts the error: "Input string was not in a correct format". As I'm new with the language I would appreciate some assistance.
This is the code I'm using:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0) {
label2.Text = "Miles";
label3.Text = "kilometers";
double m;
double kilometer=1.6093 ;
m = kilometer * Convert.ToDouble(textBox1.Text);//here is the problem
textBox2.Text = m.ToString();
I think just you need to check the value of your textbox first cause you can`t convert null value to Double
if (textBox1.Text!="")
{
m = kilometer * Convert.ToDouble(textBox1.Text);//here is the problem
textBox2.Text = m.ToString();
}
or give textBox1 initial value before start calculation,
Note: If you use number Regex for TextBox1 this will be better
Thanks.
I'm creating a calculator and I want to add validation code in it, so that if anything besides numbers is entered, an error message appears.
private void button4_Click(object sender, EventArgs e)
{
int R = Convert.ToInt32(textBox1.Text);
int I = Convert.ToInt32(textBox2.Text);
int number2;
if (int.TryParse(textBox1.Text, out number2))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
textBox2.Text = ("value entered is not whole number");
}
}
This is the code I am trying to use but it comes up with an error message when I enter a non-numeric value.
You are calling Convert.ToInt32 method before TryParse and that causes the exception. Don't do that, do the validation with TryParse.
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R) &&
int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else
{
MessageBox.Show("You have entered an invalid value!");
}
}
Also you might consider using more descriptive variable names instead of E, R, I...
private void button4_Click(object sender, EventArgs e)
{
int R, I;
if (int.TryParse(textBox1.Text, out R)
&& int.TryParse(textBox2.Text, out I))
{
int E = R - I;
textBox3.Text = E.ToString();
}
else { textBox3.Text = ("value entered is not whole number"); }
}
Make sure you try to parse the strings into ints with TryParse always, rather than just converting immediately... if there are letters, the conversion fails.
private void button4_Click(object sender, EventArgs e)
{
int number1;
int number2;
if (int.TryParse(textBox1.Text, out number1) && int.TryParse(textBox2.Text, out number2))
{
//do your thang (subtraction, assigning the result to TextBox3)
//return
}
else
{
MessageBox.Show("Oh no you entered something that's not an int!");
}
}
I might also add that making the value of one of your input text boxes "Value entered is not a whole number" is kind of a weird UI experience. I'd mark the textbox in red or pop up a message box or something instead, leaving the entered value in the box, in case it was some really long number like 879320!78 where they accidentally entered a weird symbol or something.
I have the following code in my TextBox leave event:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
But if move back to the previous control by hitting Shift+Tab and again moving back to the same textbox and then trying to move to other the form is getting closed automatically. Why does this happen?
The call to Convert.ToInt32() is probably throwing an exception, likely due to being unable to convert the string in your TextBox to an integer. Convert.ToInt32() can throw the following exceptions (descriptions from MSDN):
FormatException - value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException - value represents a number that is less than Int32.MinValue or greater than Int32.MaxValue.
It's likely a FormatException, thrown when you leave the TextBox after the $ is prepended to your string, or after you enter any non-numeric characters (letters, etc). To fix this, you have a couple of options:
Add a try / catch block around your code to handle any exceptions.
Use Int32.TryParse() instead of Convert.ToInt32().
Add some code that will prevent non-numeric characters from being entered in your TextBox
Here's an improved version of your event handler:
private void txtAmount_Leave(object sender, EventArgs e)
{
string toParse = txtAmount.Text.TrimStart('$');
int parsed;
if (Int32.TryParse(toParse, out parsed))
{
double res = (double)parsed / 100;
txtAmount.Text = "$" + res.ToString();
}
}
The first time you leave this textbox, its contents will be changed to "$123" (for example). The second time you leave, trying to convert that to int will throw an exception.
You could use the overload of TryParse that takes a NumberStyle, something like this, assuming your goal is to just show a currency value with no decimal places.
double number;
if (double.TryParse(txtAmount.Text, NumberStyles.Currency, CultureInfo.CurrentUICulture, out number))
{
txtAmount.Text = number.ToString("C0");
}
else
{
MessageBox.Show("Could not convert.");
}
After reading #Donut's comment on his answer, I am not sure what your goal is. If you'd like to truncate the cents off but still show the ".00", you can do this:
txtAmount.Text = ((int)number).ToString("C");
Or do this, which will round:
txtAmount.Text = (Convert.ToInt32(number)).ToString("C");
If this does not help, please clarify and let us know what you are trying to accomplish.
Try this:
private void txtAmount_Leave(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txtAmount.Text) && txtAmount.Text.StartsWith("$"))
txtAmount.Text = txtAmount.Text.Substring(1);
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
Check the txtAmount.Text for the $ sign, before trying to convert it to an int. If the $ sign is present, strip it out, and convert the rest of the input to an int.
Also, you might want to use the Int32.TryParse method, as that will help you figuring out whether the entered text can be converted into an int or not.
You may want to change your code to remove the $ before working with the number:
private void txtAmount_Leave(object sender, EventArgs e)
{
int x = 0;
int.TryParse(txtAmount.Text.Replace("$", string.Empty), out x);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
}
I got the solution
private void txtAmount_Leave(object sender, EventArgs e)
{
string strAmnt = string.Empty;
strAmnt = txtAmount.Text;
if (strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
txtAmount.Text = "$" + strAmnt;
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
else
if (strAmnt.Contains("$") && !strAmnt.Contains("."))
{
Int64 amnt = 0;
strAmnt = strAmnt.Replace("$", "");
try
{
amnt = Convert.ToInt64(strAmnt);
double amt = (double)amnt / 100;
txtAmount.Text = "$" + amt.ToString();
}
catch (FormatException ie)
{
MessageBox.Show("Invalid Format");
}
}
else
if (!strAmnt.Contains(".") && !strAmnt.Contains("$"))
{
try
{
int x = Convert.ToInt32(txtAmount.Text);
double res = (double)x / 100;
txtAmount.Text = "$" + res.ToString();
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
catch (FormatException ie)
{
MessageBox.Show("InvalidFormat");
}
}
while (txtAmount.Text.Length - txtAmount.Text.IndexOf(".") <= 2)
{
txtAmount.Text += "0";
}
}
I am building a simple calculator( add + Multiply two numbers) using Windows Form Application
the code is working now but its when i try to validate it.
private void txtBtn1_Click(object sender, EventArgs e)
{
double a, b, c; // Declearing Variables
a = double.Parse(txtBox1.Text);
b = double.Parse(txtBox2.Text);
c = a + b;
txtLbl.Text = c.ToString();
}
I have tried this check:
if (int.TryParse(txtBox.Text, out int tempNum1) == false)
return;
and somthing like this:
if ((int.TryParse(txtBox1.Text, out int num1) == false) &&
(int.TryParse(txtBox1.Text, out int num2) == false))
MessageBox.Show("Please Enter a Number");
return;
Yes, you should use TryParse, e.g.
private void txtBtn1_Click(object sender, EventArgs e)
{
if (double.TryParse(txtBox1.Text, out double a) &&
double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString(); // if both TextBoxes have valid values
else {
// At least one TextBox has invalid Text
txtLbl.Text = "???";
}
}
If you want to help user in error correction we can name the invalid argument and put a keyboard focus on it:
private void txtBtn1_Click(object sender, EventArgs e) {
if (double.TryParse(txtBox1.Text, out double a)) {
if (double.TryParse(txtBox2.Text, out double b))
txtLbl.Text = (a + b).ToString();
else {
if (txtBox2.CanFocus)
txtBox2.Focus();
MessageBox("Mot a Valid 'B' Number");
}
}
else {
if (txtBox1.CanFocus)
txtBox1.Focus();
MessageBox("Mot a Valid 'A' Number");
}
}
An alternative to avoid doing any manual validation is to swap your text box for a NumericUpDown component, it does all the validation for you and works the same as a textbox.
Or you could use regex.
string compare = "1234";
Regex regex = new Regex(#"^\d$");
if (regex.IsMatch(compare))
{
//It is only numbers
}