6

The string format data with mostly 4 decimal places needs to be converted into int. I have tried this one but does not work and even directly using this Convert.ToInt16() but still did not worked:

Int32 result;
bool status = Int32.TryParse(v, out result);

Is there other ways to convert this?

Thanks.

Jen143
  • 815
  • 4
  • 17
  • 42

3 Answers3

10

You can convert it to Double first, and then convert to Int32

String s = "1.0000";
Double temp;

Boolean isOk = Double.TryParse(s, out temp);

Int32 value = isOk ? (Int32) temp : 0;
Tink
  • 132
  • 2
  • 11
Artem Popov
  • 344
  • 2
  • 11
3

You can use the following:

string data = "1.0000";
int number
if(data.Contains('.'))
    number = int.Parse(data.Substring(0, data.IndexOf('.'))); //Contains decimal separator
else
    number = int.Parse(data); //Contains only numbers, no decimal separator.

Because 1.0000 has decimal places, first strip those from the string, and then parse the string to int.

SynerCoder
  • 12,493
  • 4
  • 47
  • 78
  • Throws an exception if there is no point (or comma instead), and also interprets `10.000.000` as 10 instead of 10 million (with point as group separator) – Tim Schmelter Sep 02 '16 at 08:38
  • @TimSchmelter the question is about a number with a point as decimal separator. This means that the culture is so that a point will not be a group separator. I agree with lack of point, will improve – SynerCoder Sep 02 '16 at 08:57
1

You have to parse it as decimal and then cast to int.

decimal resultTmp;
bool status = Decimal.TryParse("1.000".Replace(".",","), out resultTmp);
int result = (int)resultTmp;

Also change '.' to ','

Enigmativity
  • 113,464
  • 11
  • 89
  • 172