c# - 系统.FormatException : Input string was not in a correct format

标签 c# visual-studio-2010 formatexception

    private void ReadUnitPrice()
    {
        Console.Write("Enter the unit gross price: ");
        unitPrice = double.Parse(Console.ReadLine());
    }

这应该可行,但我遗漏了一些明显的东西。每当我输入 double 时,都会出现错误:System.FormatException:输入字符串的格式不正确。 请注意,“unitPrice”被声明为 double 值。

最佳答案

可能是您使用了错误的逗号分隔符号,或者甚至在指定 double 值时出现了其他错误。 无论如何,在这种情况下你必须使用 Double.TryParse()就异常而言是安全的方法,并允许指定格式提供程序,基本上是要使用的文化。

public static bool TryParse(
    string s,
    NumberStyles style,
    IFormatProvider provider,
    out double result
)

The TryParse method is like the Parse(String, NumberStyles, IFormatProvider) method, except this method does not throw an exception if the conversion fails. If the conversion succeeds, the return value is true and the result parameter is set to the outcome of the conversion. If the conversion fails, the return value is false and the result parameter is set to zero.

编辑:回复评论

if(!double.TryParse(Console.ReadLine(), out unitPrice))
{
    // parse error
}else
{
   // all is ok, unitPrice contains valid double value
}

你也可以试试:

double.TryParse(Console.ReadLine(), 
                NumberStyle.Float, 
                CultureInfo.CurrentCulture, 
                out unitPrice))

关于c# - 系统.FormatException : Input string was not in a correct format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7532801/

相关文章:

c# - 设置 Size 属性时 Winform 不会调整大小

c# - .net 中 [compare ("")] 数据注释的对面?

visual-studio-2010 - VS2010 中的 SQL 2012 架构/数据比较

c# - Decimal.Parse 抛出 FormatException

c# - lambda 表达式中的子句

c# - 在 Html.DropDownList 中显示 XML 文件内容

c - 为什么我的程序在读取 txt 文件之前就停止了?

c++ - 我可以将列表放入结构中吗?

c# - 格式异常毫米:ss

java - 如何使用 Jackson 的本地化小数点分隔符反序列化浮点值