Home > Enterprise >  Issue when converting string to long in c#
Issue when converting string to long in c#

Time:12-13

I want to convert string to Long. But I got this error:

Input string was not in a correct format

How to convert string to long in C#?

I follow this answer How could I convert data from string to long in c#

This is my code:

if (Convert.ToInt64("140.82") >= minPrice && 
    Convert.ToInt64(217.76) <= maxPrice) 
{
    // do filter
}  // on this line the exception is thrown

What is the mistake I made?

CodePudding user response:

You cannot convert "140.82" to long value in C#. You can convert "140.82" to double and then convert to long.

(long)double.Parse("140.82")

CodePudding user response:

You are converting the string to an integer, not a long. The Convert.ToInt64() function cannot convert the decimal of the string into an int, as that would require truncating. Instead try Double.TryParse(), and then convert that to an integer. To remove the decimal so you can convert it to an int after converting it to a double, use either Math.Floor(), Math.Ceiling(), Math.Round(), or Math.Truncate().

CodePudding user response:

If you are going to use the Convert.ToInt64(param) method to convert string data to long, it is expected that the current data format should conform to the target data format. If the Convert.ToInt64() method is to be used, the string data must be in long format.

int minPrice = 100;

if(minPrice <= Convert.ToInt64("140"))
{
    Console.WriteLine("Value: {0}", Convert.ToInt64("140"));
}

The other method is to use the Convert.ToDouble() method if you are sure the string is in floating point format:

int minPrice = 100;

if(minPrice <= (long)Convert.ToDouble("140.82"))
{
    Console.WriteLine("Value: {0}", Convert.ToDouble("140.82"));
}
  • Related