Earth
Earth

Reputation: 3571

How to parse the value to float?

Code:

float rt = float.Parse("12.50%");

I am getting the error message as

System.FormatException: Input string was not in a correct format.

How to parse a value to float?

Upvotes: 0

Views: 117

Answers (3)

Freelancer
Freelancer

Reputation: 9074

It is due to '%' sign in 12.50%

pasring is done in the same way you did it or,

float.TryParse also you can use .

Upvotes: 0

Habib
Habib

Reputation: 223237

float rt = float.Parse("12.50%".Replace("%",""));

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500175

It's the % which is causing a problem here. Either use DecimalFormat with a custom pattern, or strip the % before you parse.

You should also be aware of cultural context - will the input always use . as the decimal separator, or do you need to use the locale of the supplier of the value? For example, in some locales this would be represented as "12,50%".

Upvotes: 4

Related Questions