Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert string("1.0000") to int

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.

like image 553
Jen143 Avatar asked Sep 02 '16 08:09

Jen143


People also ask

How to Convert decimal string to Integer in c#?

string value = "34690.42724"; Convert. ToInt64(Convert. ToDouble(value)); c#

How do you convert strings to decimals?

ToDecimal(String, IFormatProvider) Converts the specified string representation of a number to an equivalent decimal number, using the specified culture-specific formatting information.

How do I convert string to int to split?

Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer.


2 Answers

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;
like image 52
Artem Popov Avatar answered Oct 28 '22 01:10

Artem Popov


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.

like image 3
SynerCoder Avatar answered Oct 28 '22 03:10

SynerCoder