0

a C# beginner here. I've been following a guide on making a simple calculator. Everything worked fine 'till I added the point button. If I use the calculator to calculate basic integers there's no problem. However, when I add in the point button to calculate doubles with a decimal it gets all screwed up. Any ideas?

    // Above this are the numeric buttons, no problem with those

    private void btnPoint_Click(object sender, EventArgs e)
    {
        txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
    }

    double total1 = 0; 
    double total2 = 0; 

    private void btnPlus_Click(object sender, EventArgs e)
    {
        total1 = total1 + double.Parse(txtDisplay.Text); // Error comes here
        txtDisplay.Clear();
    }

    private void btnEquals_Click(object sender, EventArgs e)
    {
        total2 = total1 + double.Parse(txtDisplay.Text); // And one time it came here
        txtDisplay.Text = total2.ToString(); 
        total1 = 0; 
    }
FeliceM
  • 4,163
  • 9
  • 48
  • 75

2 Answers2

0

Time ago I've made a simple calculator and for checking the input I have used regex(if you don't know what is a Regex take a look here

You can use this regex for checking the input: ^[0-9]{0,}([.,][0-9]{1,})?$ It allows:

0
10 
100
1,2
1.2

But not

.1
,1
 And all type of string

For using the regex in c# you must declare a Regex object. Before that you need to add using System.Text.RegularExpressions; Than use the regex is quite simple

Regex regex=new Regex(pattern);
if(regex.IsMatch(myTextBox.Text))
{//Do something
}
else{//Catch the error
}

If you want know more about regular expression take a look here

Tinwor
  • 7,765
  • 6
  • 35
  • 56
-1

Instead of using Double.Parse use Double.TryParse.

private void btnPlus_Click(object sender, EventArgs e)
{
    Double v = 0;
    if ( Double.TryParse(txtDisplay.Text.Trim(), out v)
    {
        total1 = total1 + v;
        txtDisplay.Clear();
    }
    else
    {
        // Invalid value
    }

}
Muhammad Umar
  • 3,761
  • 1
  • 24
  • 36
  • 2
    [`Double.TryParse()` differs from the Double.Parse(String) method by returning a Boolean value that indicates whether the parse operation succeeded instead of returning the parsed numeric value.](http://msdn.microsoft.com/en-us/library/994c0zb1(v=vs.110).aspx) This doesn't resolve OP's problem as the parsing will still fail, it just returns a boolean instead of throwing an exception. – CodeCaster Nov 16 '13 at 17:55