[c#] How could I convert data from string to long in c#

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;

This question is related to c# string type-conversion long-integer

The answer is


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...


You can create your own conversion function:

    static long ToLong(string lNumber)
    {
        if (string.IsNullOrEmpty(lNumber))
            throw new Exception("Not a number!");
        char[] chars = lNumber.ToCharArray();
        long result = 0;
        bool isNegative = lNumber[0] == '-';
        if (isNegative && lNumber.Length == 1)
            throw new Exception("- Is not a number!");

        for (int i = (isNegative ? 1:0); i < lNumber.Length; i++)
        {
            if (!Char.IsDigit(chars[i]))
            {
                if (chars[i] == '.' && i < lNumber.Length - 1 && Char.IsDigit(chars[i+1]))
                {
                    var firstDigit = chars[i + 1] - 48;
                    return (isNegative ? -1L:1L) * (result + ((firstDigit < 5) ? 0L : 1L));    
                }
                throw new InvalidCastException($" {lNumber} is not a valid number!");
            }
            result = result * 10 + ((long)chars[i] - 48L);
        }
        return (isNegative ? -1L:1L) * result;
    }

It can be improved further:

  • performance wise
  • make the validation stricter in the sense that it currently doesn't care if characters after first decimal aren't digits
  • specify rounding behavior as parameter for conversion function. it currently does rounding

long l1 = Convert.ToInt64(strValue);

That should do it.


You can also do using Int64.TryParse Method. It will return '0' if their is any string value but did not generate an error.

Int64 l1;

Int64.TryParse(strValue, out l1);

You can also use long.TryParse and long.Parse.

long l1;
l1 = long.Parse("1100.25");
//or
long.TryParse("1100.25", out l1);

You won't be able to convert it directly to long because of the decimal point i think you should convert it into decimal and then convert it into long something like this:

String strValue[i] = "1100.25";
long l1 = Convert.ToInt64(Convert.ToDecimal(strValue));

hope this helps!


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.


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
)

long is internally represented as System.Int64 which is a 64-bit signed integer. The value you have taken "1100.25" is actually decimal and not integer hence it can not be converted to long.

You can use:

String strValue = "1100.25";
decimal lValue = Convert.ToDecimal(strValue);

to convert it to decimal value


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift

Examples related to long-integer

"OverflowError: Python int too large to convert to C long" on windows but not mac How to check a Long for null in java What is the difference between "long", "long long", "long int", and "long long int" in C++? java.math.BigInteger cannot be cast to java.lang.Long A long bigger than Long.MAX_VALUE Definition of int64_t How to convert string to long Convert python long/int to fixed size byte array Converting Long to Date in Java returns 1970 Division of integers in Java