【问题标题】:Issue when converting string to long in c#在c#中将字符串转换为long时的问题
【发布时间】:2022-01-16 14:36:01
【问题描述】:

我想将字符串转换为 Long。但是我收到了这个错误:

输入的字符串格式不正确

如何在 C# 中将字符串转换为长字符串?

我关注这个答案How could I convert data from string to long in c#

这是我的代码:

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

我犯了什么错误?

【问题讨论】:

  • 请注意,该问题的最高投票答案实际上是错误的,并且会给您该错误。
  • 既然您在代码中输入值,为什么不将它们输入为十进制而不是字符串(在 217.76 的情况下输入其他内容)?

标签: c# asp.net-core


【解决方案1】:

您不能在 C# 中将“140.82”转换为长值。您可以将“140.82”转换为double,然后再转换为long。

(long)double.Parse("140.82")

【讨论】:

    【解决方案2】:

    您正在将字符串转换为整数,而不是长整数。 Convert.ToInt64() 函数无法将字符串的小数转换为 int,因为这需要截断。而是尝试 Double.TryParse(),然后将其转换为整数。要删除小数,以便在将其转换为双精度后将其转换为 int,请使用 Math.Floor()、Math.Ceiling()、Math.Round() 或 Math.Truncate()。

    【讨论】:

    • 嗯,long 是一个整数,但是是的,问题是十进制值。
    【解决方案3】:

    如果你打算使用Convert.ToInt64(param)方法将字符串数据转换为long,期望当前数据格式应该符合目标数据格式。如果要使用Convert.ToInt64()方法,字符串数据必须是长格式。

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

    如果您确定字符串是浮点格式,另一种方法是使用Convert.ToDouble() 方法:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多