How to Convert string("1.0000") to int
Asked Answered
S

3

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.

Scriabin answered 2/9, 2016 at 8:30 Comment(2)
Try using Convert.ToInt32().Clodhopper
Why don't you use decimal.TryParse?Dunaway
O
11

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;
Obregon answered 2/9, 2016 at 8:49 Comment(0)
F
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.

Flinch answered 2/9, 2016 at 8:34 Comment(2)
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)Dunaway
@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 improveFlinch
M
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 ','

Mcfadden answered 2/9, 2016 at 8:36 Comment(2)
why change '.' to ','? this would depend on the culture.Seta
yes, its better to give CurrentCulture as argument. I had to change it because in mine it is not correct format.Mcfadden

© 2022 - 2024 — McMap. All rights reserved.