Igor
Igor

Reputation: 329

Can't parse text to Decimal

In Form_load I have

txtAlteFonduri.Text = "5,00";
txtFReparatii.Text = "15,00";
txtFRulment.Text = "20,00";

and in another function I want to parse text as decimal

decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text);
decimal fondRulment = Decimal.Parse(txtFRulment.Text);
decimal fondRepar = Decimal.Parse(txtFReparatii.Text);

but I have an error in the second line

Input string was not in a correct format.

Upvotes: 0

Views: 1230

Answers (3)

Daniel Brückner
Daniel Brückner

Reputation: 59645

You have to use this overload of Decimal.Parse and supply a IFormatProvider matching the culture of your input. You should also consider using one of the Decimal.TryParse methods for better error handling.

Upvotes: 1

chrisc
chrisc

Reputation: 434

You are using a different culture to what decimal.Parse() is expecting (it expects the decimal point '.' but you provide a comma. Using the correct culture should correctly parse the strings, although I can run your code without having any errors...

You can use Decimal.Parse(variable, CultureInfo.GetCultureInfo("Culture-Name"));

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

You need to specifically add the number format. For your examples above, the following should work:

decimal alteFonduri = Decimal.Parse(txtAlteFonduri.Text, CultureInfo.GetCulture("de-DE"));

Otherwise, the system's culture information is used.

Upvotes: 7

Related Questions