使用以下参数调用CorrectDecimals时出现完全错误:
203,30 - 203,00。给我:0.30000000000001137(变量double d)。凭借我的数学技能,它应该只有0.3
string a = CorrectDecimals("203,30", "203,00", "12");
public static string CorrectDecimals(string unitPrice, string netAmount, string length)
{
double unitP = (Double.Parse(unitPrice));
double netAmoun = (Double.Parse(netAmount));
double d = unitP - netAmoun;
答案 0 :(得分:2)
使用财务数据(价格,金额等)时,请使用Decimal
代替double
/ float
:
string a = CorrectDecimals("203,30", "203,00", "12");
public static string CorrectDecimals(string unitPrice, string netAmount, string length)
{
decimal unitP = decimal.Parse(unitPrice);
decimal netAmoun = decimal.Parse(netAmount);
decimal d = unitP - netAmoun;
如果您必须在double
中实施例程,请使用格式:
double d = unitP - netAmoun;
...
// 2 digits after decimal point
string result = d.ToString("F2");
答案 1 :(得分:0)
public static string CorrectDecimals(string unitPrice, string netAmount, string length)
{
decimal unitP = (decimal.Parse(unitPrice));
decimal netAmoun = (decimal.Parse(netAmount));
decimal d = unitP - netAmoun;
string result = d.ToString();
return result;
}
使用小数而不是双倍。