2

i have an Person object with an age property (int)

i am parsing a file and this value is coming in this format "6.00000000000000"

what is the best way to convert this string into an int in C#

Convert.ToInt32() or Int.Parse() gives me an exception:

Input string was not in a correct format.

leora
  • 188,729
  • 360
  • 878
  • 1,366
  • did you even search for this? It's a duplicate of http://stackoverflow.com/questions/2344411/how-to-convert-string-to-integer-in-c – msarchet Oct 10 '10 at 13:59
  • possible duplicate of [How can I convert String to Int?](http://stackoverflow.com/questions/1019793/how-can-i-convert-string-to-int) – ChrisF Oct 10 '10 at 14:02
  • 1
    @ChrisF: I don't consider this an exact duplicate. The question you linked was about converting an integer string to an `int`. This question is about converting a decimal string that happens to represent an integer value to an `int`. The difference is small but relevant: it's why the answers here include `double` and `decimal` parsing, and the `NumberStyles.AllowDecimalPoint` option. – Joren Oct 10 '10 at 14:58

2 Answers2

12

It depends on how confident you are that the input-data will always adhere to this format. Here are some alternatives:

string text = "6.00000000"

// rounding will occur if there are digits after the decimal point
int age = (int) decimal.Parse(text); 

// will throw an OverflowException if there are digits after the decimal point  
int age = int.Parse(text, NumberStyles.AllowDecimalPoint);

// can deal with an incorrect format
int age;
if(int.TryParse(text, NumberStyles.AllowDecimalPoint, null, out age))
{             
   // success
}
else
{
   // failure
} 

EDIT: Changed double to decimal after comment.

Ani
  • 111,048
  • 26
  • 262
  • 307
  • 1
    I'd rather use `decimal` than `double` for the first case. Integers should be fine, but in general parsing decimal input to binary floating point is not a good idea. Anyway, your second option is by far the most sensible, +1. If you don't want to deal with exceptions, just use TryParse instead of Parse. – Joren Oct 10 '10 at 13:58
1
int age = (int) double.Parse(str);
int age = (int) decimal.Parse(str);
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83