我一直试图让这个打印出是到小数点后两位的回答。所有参与的数学已经留在两位小数该格式。我已经尝试了一些东西,我不知道什么改变,使这项工作。
double pdt1 = 239.99;
double pdt1Total;
double pdt2 = 129.75;
double pdt2Total;
double pdt3 = 99.95;
double pdt3Total;
double pdt4 = 350.89;
double pdt4Total;
double wage = 200;
double percentage = 9;
double total;
double answer;
double i = 100;
double a;
double b;
double c;
double d;
Console.Write("Enter number sold of product #1: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #2: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #3: ");
c = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter number sold of product #4: ");
d = Convert.ToInt32(Console.ReadLine());
pdt1Total = a * pdt1;
pdt2Total = b * pdt2;
pdt3Total = c * pdt3;
pdt4Total = d * pdt4;
total = (pdt1Total + pdt2Total + pdt3Total + pdt4Total);
string.Format("{0:0.00}", total);
string.Format("{0:0.00}", answer = (total * percentage / i) + wage);
Console.WriteLine("Earnings this week: "+answer+"");
string.Format
不会改变原有的价值,但它会返回一个格式化字符串。例如:
Console.WriteLine("Earnings this week: {0:0.00}", answer);
注:Console.WriteLine
允许内嵌的字符串格式化。以上是等效于:
Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));
那么,根据你的需要,你可以选择以下任何一种。走出看跌期权对每个方法写入
你可以选择你需要的
这将圆
decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
这将确保小数点后2位被写入。
d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
如果你想要写逗号,你可以使用这个
d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
如果你想返回十进制值的圆角,你可以这样做
d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
你能让一个double
到小数点后两位是这样的:
double c;
c = Math.Round(c, 2);
但要注意四舍五入最终会咬你,所以请谨慎使用。
而是使用decimal
数据类型。
既然你是在货币工作为什么不直接这样做:
public string ValueAsString(double value, int decimalPlaces)
{
return value.ToString($"F{decimalPlaces}");
}
这将格式化的回答为货币,所以我的机器(UK)上会出来为:
收益本周:£209.00
问题是,当你在做加法和数字的乘法都保留两位小数,您预计不会有舍入误差,但要记住内部表示双在基地2,不要在基地10!因此,在基部10的数字等0.1可以是在基体2:0.101010101010110011 ...带有小数的无限数量(存储在双值将是与多个N:
Console.Writeline("Earnings this week: {0:c}", answer);
因此像12.3 + 0.1的操作可以是不完全相同的64位的双值12.4(或12.456 * 10可以是如124.56不一样),因为舍入误差。例如,如果你在数据库中的12.3 0.1结果存储到的类型的双精度数的表/列字段,然后选择其中xx = 12.4您可能意识到你存储一个数字,是不完全12.4和SQL选择意愿不返回记录;所以,如果你不能使用十进制数据类型(其内部表示以10为基数),并且必须使用“双”的数据类型,你需要做的每一个加法或乘法之后一些标准化:
0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64)