简体   繁体   中英

Error in calculation Winforms C#

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM