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);
Related
This is one of those cases where I assume the solution is on google, but I have no idea what the search term even is. Or even which Tags to use on Stack Overflow.
Situation:
Floats are not precise. A common trick around it, is to use Integers for the math, then shift the decimal point during output:
If you need 4 decimal places of precision for € (not uncommon in finances), you effectively measure and calculate in milli-Euro. Then during output you shift the decimal left, and cut off the last 2 digits:
So a int 1234567 that is stored, retrieved and processes as a int, would print as/stand for "123.45 €" to the normal end user.
Problem:
But how would this interact with localisation? .NET has this awesome part where Parse() and ToString() look at the current Windows Users Culture setting, to figure out what the decimal separator, group separator and group size is today.
There seems to be no fixed point type in .NET, to do the work for me.
Is there some format string combination I could use to say "shift decimal point 4 left into the number, omit last 2 digits)"? F2 would only add two empty 0 past the decimal point for any int. and "1234567.00 €" is a few orders of magnitude off from "123.45 €"
My best idea thus far:
Building my own format string out of the NumberDecimalSeparator, NumberGroupSeparator and NumberGroupSizes from the users culture - but that is just ugly and seems like something I should not be doing. Is there a better day to do it, or is it one of those cases where I have to go for the ugly thing that works?
Maybe something like this
using System.Globalization;
int n = 123456;
string price = "";
string priceW = "";
int i = 0;
foreach(char c in n.ToString())
{
i++;
if(i == n.ToString().Length - 1)
price += ".";
price += c;
}
float rPrice = float.Parse(price, CultureInfo.InvariantCulture.NumberFormat);
priceW = price + "€";
I'm New to C# with Xamarin. Im using Visual Studio for Mac Preview to work on an iOS app.
When Making a basic calculator I can't figure out how to not accept answers that aren't a numeric digit. For example in my Text box if I put in a letter I want an error that says
"Please enter a numeric digit".
I don't know why I'm getting an error but its not working.
When I run it and put in a number it just defaults to the else statement every time. Also with Letters. And when I put too many letters in it crashes.
partial void AddButton_TouchUpInside(UIButton sender)
{
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
int value;
string input = Console.ReadLine();
if (Int32.TryParse(input, out value))
{
number1 = double.Parse(Number1TextBox.Text);
number2 = double.Parse(Number2TextBox.Text);
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
}
I think the problem is string input = Console.ReadLine();
Why are you expecting a correct value with that statement? That would be valid for a console program but you are running an iOS app.
It would make sense something like:
string input = YourTextInput.Text;
If you want to restrict the text input to a keyboard with numbers, use the following:
YourTextInput.KeyboardType = UIKeyboardType.NumberPad;
And one more thing. If the answer should be a double, you should use double.TryParse(input, out value) instead of int.
What about this?
double number1 = 0.00;
double answer = 0.00;
double number2 = 0.00;
if (double.TryParse(Number1TextBox.Text, out number1)
&& double.TryParse(Number2TextBox.Text, out number2))
{
answer = number1 + number2;
AnswerLabel.Text = "The answer is: " + answer.ToString();
}
else
{
InvalidLabel.Text = "Please enter a Numeric Digit";
}
You still need to validate the number entered, as the number pad allows to type more than one decimal point.
I'd recommend changing the TextBox so the keyboard which appears is numeric only.
<Entry Keyboard="Numeric" />
Check out this Xamarin Guide for more info.
I am just beggining coding, and cant find a solution in my textbook, as Im studying from home to later validate in a noob programme course, I dont have a teacher to ask..
C#
Console.Write("write a interger between 1 and 100: ");
string anvS = Console.ReadLine();
int anvI;
if (int.TryParse(anvS, out anvI))
{
if (anvI < 100)
{
while (anvI <= 100)
{
Console.Write(anvI++ + " ");
}
Console.ReadKey();
}
else
{}
}
else
{}
The problem:
As you can see it cuts of the format in the upper right.
Also, as im somewhat a newbie, is there a easy fix that not to complicated, and whats the more advanced fix?
This is how the Windows console works, you can change the size of the console through the Console class.
You could also write each number on a new line, or collect your numbers in an array and write them out in a formatted table at the end.
List<int> listOfNumbers = new List<int>();
Replace your Console.Write line with listOfNumbers.Add(anvI++);
The write your output at the end:
for (int i = 0; i < 100; i += 5)
{
Console.WriteLine(string.Join(" ", listOfNumbers.Skip(i).Take(5)));
}
The Windows console has two widths, measured in characters. One is the buffer width - how many available characters you have in a single line. The other is the window width - how wide your actual console window is. If your buffer width is bigger than your window width, your console will have a horizontal scrollbar. You can see and set them if you right-click the console title bar and click Properties.
The console doesn't care about words, it just wraps at exactly that many characters, default being 80. To prevent this, you would need to word-wrap manually - format your output so that it doesn't go over whatever your console width is set to. You can get (and set) the widths using Console.BufferWidth and Console.WindowWidth respectively.
Here is one way to do what you want:
Console.Write("Write an interger between 1 and 100:");
string inputS = Console.ReadLine();
int inputI;
if (int.TryParse(inputS, out inputI) && inputI < 100)
{
var lineBuilder = new StringBuilder();
while (inputI <= 100)
{
var numStr = inputI + " ";
if (lineBuilder.Length + numStr.Length > Console.WindowWidth)
{
Console.WriteLine(lineBuilder.ToString());
lineBuilder.Clear();
}
lineBuilder.Append(numStr);
inputI++;
}
if (lineBuilder.Length > 0)
{
Console.WriteLine(lineBuilder.ToString());
}
Console.ReadKey();
}
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.
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.