我可以将一个字符串变为货币格式而不是另一个。该计划的目的是计算2014年的税收支付金额,并显示收入水平所需的税收以及您将带回家的税额。
private void calculate_Click(object sender, RoutedEventArgs e)
{
double income = double.Parse(taxInput.Text);
taxOutput.Text = calculateTaxes(income);
takeHome.Text = calculateTakeHome(taxOutput.Text, income);
}
private string calculateTakeHome(string p, double income)
{
double numOne = double.Parse(p);
double outcome = income - numOne;
return outcome.ToString("C2");
}
private string calculateTaxes(double income)
{
double total;
if (income > 406750)
{
total = bracketSeven(income);
}
else if (income > 405100)
{
total = bracketSix(income);
}
else if (income > 186350)
{
total = bracketFive(income);
}
else if (income > 89350)
{
total = bracketFour(income);
}
else if (income >36900)
{
total = bracketThree(income);
}
else if (income > 9075)
{
total = bracketTwo(income);
}
else
{
total = bracketOne(income);
}
return total.ToString();
}
private double bracketOne(double income)
{
double tax = income * .1;
return tax;
}
private double bracketTwo(double income)
{
double tax = ((income - 9075) * .15) + 907.5;
return tax;
}
private double bracketThree(double income)
{
double tax = ((income - 36900) * .25) + 5081.25;
return tax;
}
private double bracketFour(double income)
{
double tax = ((income - 89350) * .28) + 18193.75;
return tax;
}
private double bracketFive(double income)
{
double tax = ((income - 186350) * .33) + 45353.75;
return tax;
}
private double bracketSix(double income)
{
double tax = ((income - 405100) * .35) + 117541.25;
return tax;
}
private double bracketSeven(double income)
{
double tax = ((income - 406750) * .396) + 118188.75;
return tax;
}
我可以使用return outcome.ToString("C2")
以货币格式显示takeHome.Text,但是当我把" C2"像这样的calculateTaxes()函数:return total.ToString("C2");
我得到一个错误,说我的解析是不正确的。程序编译但在我尝试计算时抛出异常。
我试图用" C2"解析它。在大约5种其他方式中它仍然会抛出相同的异常,任何想法?
答案 0 :(得分:0)
问题是您尝试使用货币符号将字符串解析为double。您可以使用格式化来完成此操作。例如,您可以尝试下面的内容
private static string calculateTakeHome(string p, double income)
{
double numOne = double.Parse(p,System.Globalization.NumberStyles.Currency);
double outcome = income - numOne;
return outcome.ToString("C2");
}