I have:
textbox1.text == 1.4087
textbox2.text == 521.54
It's not hardcoded, I get it from JSON. Anyway, I want to multiply these two numbers.
I use this code:
double curr = 0.0;
double price = 0.0;
double multiply = 0.0;
double.TryParse(textBox1.Text, out curr);
double.TryParse(textBox2.Text, out price);
multiply = curr * price;
textBox3.Text = multiply.ToString();
I also tried with Convert.ToDouble still no luck.
I always get 0 in textBox3. Apparently the strings are not recognized as double. But they are. Any ideas? Thanks!
EDIT: From JSON:
{"high": "567.88", "last": "543.95", "timestamp": "1394987785",
I'm using this code to get what i need:
Regex expression = new Regex(#"last"":\s""(?<Identifier>[0-9]+\.[0-9]+)");
var results = expression.Matches(Cryp);
foreach (Match match in results)
{
textBox1.Text = match.Groups["Identifier"].Value;
}
Any issues here?
Try This:
double.TryParse(textBox1,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out curr);
double.TryParse(textBox2.Text,NumberStyles.AllowDecimalPoint,
CultureInfo.InvariantCulture, out price);
multiply = curr * price;
I would assume one of the TryParse calls fails resulting in it keeping a value of 0 so regardless of what the working one is, you're going to get 0 for a result.
I just wrote up a basic ASP.NET application with three textboxes and then just pasted your code without changing anything into the event handler for a submit button. Manually typing the two numbers you provided gave the correct answer of 734.693398 in TextBox3. Your inputs must be off.
Related
double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
if (!double.tryParse(strx, out double a))
{MessageBox.Show("Incorrect input");}
else if (!double.tryParse(stry, out double b))
{MessageBox.Show("Incorrect input");}
x = a;
y = b; <---
The problem is that x and receive value of a, but y cant do the same for b.
I understand its because its within 'else' and might not get executed, but if I remove the else, then if both textboxes are empty or not numbers I'll get two error popups...
Any help resolving the issue?
You should question how your logic is set.
Right now, if either or both textboxes are wrong, the user sees the ambiguous "Incorrect input". I would find this frustrating. Where's the incorrect input? Is it the first text box? The second? Both?
As you develop better UIs, the answer will be to validate each text box and have each one that is wrong turn a color or provide some other feedback on the form itself. Otherwise, imagine how ugly the logic will get when you're presenting a form to the user with 20 different fields.
However, if you're only going to use two fields, and you want to have some logic, try something like this (note that in doing this, I got rid of the else, as well, so b will always be set):
double x;
double y;
string strx = TextBoxX.Text;
string stry = TextBoxY.Text;
List<string>() invalids = new List<string>();
if (!double.tryParse(strx, out double a))
{invalids.Add("boxX");}
if (!double.tryParse(stry, out double b))
{invalids.Add("boxY")}
if invalids.Length != 0
{MessageBox.Show("Incorrect inputs in " + String.Join(", ", invalids.ToArray());}
x = a;
y = b;
The user will enjoy a single box that tells them of all the errors more than multiple pop-up boxes, or having to hit OK each time and see that there are more errors.
if (!double.TryParse(strx, out double a) || !double.TryParse(stry, out double b))
{
MessageBox.Show("Incorrect input");
return;
}
I am building C# WinForms application which has 3 textboxes. First two take value and after calculation show value in third textbox. It has to be in textbox so user can change value if thinks that calculation is wrong. Everything works perfect, but when I run app on windows 7 I get huge error, it calculates that (for example ) 2 times 2.15 is 430. Why is that happening ? I tried installing latest .Net framework on that computer but still doesn't work and after research I have no further ideas.
num1 = num2 = sum = 0;
if (tbNum1.Text.Contains(","))
{
tbNum1.Text = tbNum1.Text.Replace(",", ".");
}
double.TryParse(tbNum1.Text, out num1);
if (tbNum2.Text.Contains(","))
{
tbNum2.Text = tbNum2.Text.Replace(",", ".");
}
double.TryParse(tbNum2.Text, out num2);
sum = num1 * num2;
sum = Math.Round(sum, 2);
tbSum.Text = sum.ToString();
Also, additional two problems appear with displaying WinForm.
First is that panels have different sizes and positions than I programatically set.
Secont is that ( and I suppose that is my fault because I am probably doing that wrong ) all panels show very slow. What I have is like 6 panels with particular dimensions and 6 buttons. Depending on pressed button, I set all panels visible to false and only correct panel visible to true. But it loads very slow. Do you have any suggestions ? Thanks a lot in advance !
Your parse to a double is wrong. You can do it like this:
double num1, num2, product = 0;
if (tb1.Text.IndexOf(",") != -1)
{
tb1.Text = tb1.Text.Replace(",", ".");
}
num1 = double.Parse(tb1.Text, System.Globalization.CultureInfo.InvariantCulture);
if(tb2.Text.IndexOf(",") != -1)
{
tb2.Text = tb2.Text.Replace(",", ".");
}
num2 = double.Parse(tb2.Text, System.Globalization.CultureInfo.InvariantCulture);
product = Math.Round(num1 * num2,2);
tb3.Text = product.ToString();
The character that double.Parse recognizes as the decimal separator depends on the supplied IFormatProvider; if you don't supply any, that's the one for the current culture.
If you specifically want to use the dot as the decimal separator, you can just use CultureInfo.InvariantCulture:
double.TryParse(tbNum2.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double num);
So there are still some logic errors in this that I am working on. I'm not worried about those, and I want to figure them out myself.
I'm working on a slot machine app for some independent study and when I try to parse the value of the label that shows the players cash into a variable I am getting a format exception. How do fix this and more importantly why am I getting this exception?
I have also tried using TryParse and Convert.ToDouble.
protected void PullBTN_Click(object sender, EventArgs e)
{
// Get players cash//////////////////////////////
double playersCash = Convert.ToDouble(playerMoneyLBL.Text);
// Other way I tried that didn't work ////////////
//double playersCash = 0;
//double.TryParse(playerMoneyLBL.Text.Trim(), out playersCash);
// Get players bet /////////////////////////////
double playerBet = 0;
if (!double.TryParse(betTB.Text, out playerBet))
return;
// Spin the slots//////////////////////////////
Image1.ImageUrl = spinReel();
Image2.ImageUrl = spinReel();
Image3.ImageUrl = spinReel();
// Find multiplier //////////////////////////////
double multiplier = findMultiplier();
// Find winnings ///////////////////////////////
double winnnings = multiplier * playerBet;
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
// Add winnings to players money //////////////
playerMoneyLBL.Text = (playersCash + winnnings).ToString();
}
Your problem is here.
playerMoneyLBL.Text = "$100";
As you have $ in-front of 100, you cannot convert that to float. Make it something like this.
double playersCash = Convert.ToDouble(playerMoneyLBL.Text.substring(1));
double.Parse uses your CurrentCulture settings on the current environment by default.
double d = double.Parse("Your Text Here", CultureInfo.InvariantCulture);
Or if you want it more secure way, try:
value = "Your String";
style = NumberStyles.Number | NumberStyles.AllowCurrencySymbol| NumberStyles.AllowThousands;
culture = CultureInfo.InvariantCulture
if (Double.TryParse(value, style, culture, out number))
{
// Write your code for true condition
}
else
{
// Write your code for false condition
}
I'm not sure if I should ask this, but the details might help on finding out :p
I have a table like this
And I'm using compute to get the interval where a double variable stands in the Variavel column
double value = 6;
double max Convert.ToDouble(DataAccess.Instance.tabela1vert0caso1W.Compute("MIN(Variavel)", "Variavel >= " + value.ToString(CultureInfo.InvariantCulture)));
double min = Convert.ToDouble(DataAccess.Instance.tabela1vert0caso1W.Compute("MAX(Variavel)", "Variavel <= " + value.ToString(CultureInfo.InvariantCulture)));
The problem here is that I get the inifity error on the double min line, however it only happens when I'm between 5 and 15, if I choose any other value, i get the program to work properly.
Any hint?
By the way I checked the value of value just before the lines, and it's still 6.
I'm not sure what the actual problem is, however, you could always use Linq-To-DataTable which is more powerful (supports the whole .NET framework) and also more readable:
var variavels = DataAccess.Instance.tabela1vert0caso1W.AsEnumerable()
.Select(row => row.Field<int>("Variavel"));
double max = variavels.Where(d => d >= value).Max();
double min = variavels.Where(d => d <= value).Min();
Its possible for the compute method to return DBNull.Value. It seems unclear when if at all the Max() function will return this, but possibly your select returns 0 rows?
I suggest you add a check for DBNull.Value and set min to value when it occurs
I'm developing a calculator in C# and I have a button that inserts a decimal point into the number. I ran into a problem where it allows the user to insert multiple decimal points into the interface, which threw everything off. I cooked up this little statement:
if ((number % 1) > 0)
{
richTextBox1.Text = richTextBox1.Text + "";
}
else
{
richTextBox1.Text = richTextBox1.Text + ".";
}
Except it doesn't do anything! Will someone please show me a way to only allow one decimal point by fixing this statement?
onButtonToInsertDecimalClick
if richTextBox1.Text.Contains(".")
return;
else
... rest of code
Wouldn't this (pseudocode) work?
Have you tried using Double.TryParse directly?
if(Double.TryParse(richTextBox1.Text, myDoubleValue) == false)
richTextBox1.Text = lastGoodValue;
else
lastGoodValue = richTextBox1.Text;
this will also, via TryParse, give your actual double variable the proper result. As long as this occurs every time richTextBox1.Text changes, the correction code should also cause the double value to remain good, since it'll trigger when Text is reverted to lastGoodValue.