首页 > 解决方案 > CultureInfo.GetCultureInfo 导致不正确的格式错误

问题描述

每次当我输入 z 作为输入时,它都会失败。我不明白问题是什么。它收到错误“System.FormatException:输入字符串的格式不正确” Dsales 是一个进入转换器以转换为美元和美分的整数。这有什么不正确的?

using System;
using static System.Console;
using System.Globalization;
class HomeSales
{
   static void Main()
   {
    string response;
    int dsales = 0;
    int esales = 0;
    int fsales = 0;
    int initial;
    string damount;
    string eamount;
    string famount;
    int damounti;
    int eamounti;
    int famounti;
    

WriteLine ("Enter a salesperson initial");
response = ReadLine();
//initial = Convert.ToInt32(response);

while (response == "d" || response == "D")
{
  WriteLine ("Enter Line of sale");
  damount = ReadLine();
  damounti = Convert.ToInt32(damount);
  dsales = dsales + damounti;
  
}

while (response == "z" || response == "Z")

{
  WriteLine("Danielle sold {0}", dsales.ToString("C", CultureInfo.GetCultureInfo("en-US")));
}
   }
}

标签: c#formatexception

解决方案


您错误地编写了控制台循环。

从您的变量声明和字符串来看,您的代码打算记录不同销售人员的销售额,并在完成销售条目时报告总销售额。

FormatException您在“输入销售行”提示后键入“z”时出现。

不要假设用户总是会输入一个有效的数字,而是在尝试解析一个数字之前添加一个条件来检查有效的输入。条件检查还应该包括提前退出循环的方法,或者至少避免解析数值的代码。

此外,当您处理解释为货币的值时,请考虑使用 System.Decimal ( decimal) 结构来存储值,因为计算会更准确。


推荐阅读