How could I convert data from string to long in c#
311,755
Solution 1
This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.
Convert.ToInt64("1100.25")
Method signature from MSDN:
public static long ToInt64(
string value
)
Solution 2
If you want to get the integer part of that number you must first convert it to a floating number then cast to long.
long l1 = (long)Convert.ToDouble("1100.25");
You can use Math
class to round up the number as you like, or just truncate...
Solution 3
You can also use long.TryParse
and long.Parse
.
long l1;
l1 = long.Parse("1100.25");
//or
long.TryParse("1100.25", out l1);
Solution 4
http://msdn.microsoft.com/en-us/library/system.convert.aspx
l1 = Convert.ToInt64(strValue)
Though the example you gave isn't an integer, so I'm not sure why you want it as a long.
Solution 5
long l1 = Convert.ToInt64(strValue);
That should do it.
Comments
-
MayureshP almost 4 years
How could i convert data from string to long in C#?
I have data
String strValue[i] ="1100.25";
now i want it in
long l1;
-
Jon Skeet almost 13 yearsLongs represent integers. You've given a non-integer. What would you want to do with that?
-
magma almost 13 yearsWhat if strValue is "1100.75" ? See: stackoverflow.com/questions/633335/…
-
love Computer science almost 13 years@magma: if you convert it into decimal then it will round off the number, i.e in this case if given number was 1100.75 then it will output 1101.
-
magma almost 13 years@charlie I was merely raising the issue, because MayP did not appear to be fully aware of the implication here. He might want to simply get rid of the non-integer part without any rounding, and that's fine, provided that it's really what he wants. Thank you though.
-
-
Andrew Savinykh almost 13 yearsThis is going to give you
FormatException
if you run this on the specified input. -
Thomas Levesque almost 13 years@zespri, no, at least not in most cultures... But it would indeed fail in cultures where the decimal separator is not "."
-
Pranesh Janarthanan over 3 yearsusing your code, this value 2037104000005652013 changed to 2037104000005651968. ?
-
Etienne de Martel about 2 yearsYou need to specify an explicit culture that treats
.
as a decimal separator (CultureInfo.InvariantCulture
would work). -
Etienne de Martel about 2 years@PraneshJanarthanan The biggest integer that can be safely represented in a
double
is2^53
, and yours is bigger than that, so when converted to a long you'll get some funky results. -
César León almost 2 yearsNot recomended when used with linq. It gives me an exception. long.Parse("1100.25") works for me