pokrate
pokrate

Reputation: 3974

Int32.Parse error FormatException

I am getting this very weird error,

Int32.Parse("455.55"); // gives Format Exception Error


[FormatException: Input string was not in a correct format.]
   System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) +9586043
   System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) +119
   System.Int32.Parse(String s) +23

Upvotes: 0

Views: 4731

Answers (5)

David Esteves
David Esteves

Reputation: 1604

As others have mentioned the value you're working with is not an integer but infact a floating point value. If you really want it to be an int you can do:

(int)double.Parse("455.55");

This will parse it to a double then cast it to an int causing the result to give you an int with the value of 455.

Upvotes: 2

oli
oli

Reputation: 34

You are trying to parse a floating point with Int32. You have to use Double.parse instead.

Upvotes: 0

Shai
Shai

Reputation: 25595

That's because you're trying to parse a variable that is not an integer

455.55

is NOT an integer, it's a double

455

is an integer.

Upvotes: 1

Rick Hoving
Rick Hoving

Reputation: 3575

What you are trying to do is to put a decimal (or double) into an integer. Try :

double.Parse("455.55");

Upvotes: 0

Jamie
Jamie

Reputation: 3931

455.55 is not an Int32 type, hence the exception. (Int32 ranges from about -2 billion to 2 billion, and are only integers, i.e. numbers with no fractional part.) If you want a decimal number, use double.Parse("455.55").

Upvotes: 2

Related Questions