C # operator total text fields

I am trying to summarize values ​​from 3 text fields with the following statement, however I cannot get it to work. 3 text fields have values ​​displayed in decimal. Error: An unhandled exception of type "System.FormatException" appeared in mscorlib.dll. Additional information: the input line was not in the correct format.

        decimal num1, num2, num3, total;
        num1 = Convert.ToDecimal(SSubTotalTextBox.Text);
        num2 = Convert.ToDecimal(SubTotalMTextBox.Text);
        num3 = Convert.ToDecimal(SubTotalTextBox3.Text);
        total = num1 + num2 + num3;
        TotalAmountTextBox.Text = Convert.ToString(total);
+3
source share
4 answers

This is not enough detail in the question, but my gut feeling tells me this is a problem:

, 40,5, , . (). 40,5 , ,

, 40.5, 40.5.

, , $ . , , , .

textBox.Text Convert.ToDecimal textBox.Text.Replace("$",""). $ .

, :

decimal num1, num2, num3, total;
num1 = Convert.ToDecimal(SSubTotalTextBox.Text.Replace("$",""));
num2 = Convert.ToDecimal(SubTotalMTextBox.Text.Replace("$",""));
num3 = Convert.ToDecimal(SubTotalTextBox3.Text.Replace("$",""));
total = num1 + num2 + num3;
TotalAmountTextBox.Text = "$ "+ total;

, Convert.ToDecimal decimal.Parse decimal.TryParse , .

+3

Convert.ToDecimal try:

 decimal dec1;
 if (!Decimal.TryParse(SSubTotalTextBox.Text, dec1)
 {
    MessageBox.Show("Error trying to convert to a decimal: " + SSubTotalTextBox.Text);
 }

, .

+2

- decimal.TryParse(), . MSDN: Decimal.TryParse Method (String, Decimal)

+2

? . decimal.Parse decimal.TryParse Convert.

Edit: I don't think culture is a problem. Even if he entered with 6.4, and the culture expects 6.4, it will usually be interpreted as a thousandth separator and will result in 64 instead of 6.4.

0
source

Source: https://habr.com/ru/post/1792005/


All Articles