TryParse error with currency string type for parameter

In my form, there is a text box that contains a number for the quantity. then in the event with the changed text this number is placed in the label text property with a currency value (for example: $ 4.00). In my button click event, I am trying to add all the values ​​from the labels. Using the following code, tryparse fails every time

int num1; string text = lbl85x11bwsub.Text; if (int.TryParse(text, out num1)) { MessageBox.Show(num1.ToString()); //testing } else { MessageBox.Show("it failed"); } 

but if I try the same using the textbox text property, it will work.

 int num2; if (int.TryParse(txt85x11bw.Text, out num2)) { MessageBox.Show(num2.ToString()); } else { MessageBox.Show("it failed"); } 
+4
source share
3 answers

@Frederik Gheysels gives you an almost complete answer to your question, except for one tiny thing. In this case, you should use NumberStyles.Currency, because your number may not only be not integer, but also contain thousands and decimal separators. While NumberStyles.AllowCurrencySymbol will only care about the currency sign. NumberStyles.Currency, on the other hand, is a composite number style. This can allow almost all other delimiters.

So this expression is likely to work:

 Decimal.TryParse(text, NumberStyles.Currency, CultureInfo.CurrentCulture, out result); 
+9
source

Try

 Decimal.TryParse(text, NumberStyles.Currency, CultureInfo.CurrentCulture, out result); 

instead of this. The number you are trying to analyze is as follows:

  • not an integer
  • contains currency symbol
+6
source

Use NumberStyles.Currency instead of NumberStyles.AllowCurrencySymbol

See How to parse a decimal string with a currency symbol?

0
source

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


All Articles