格式化双精度到两位小数

Dan*_*nes 40 c# format double

我一直试图将这个打印出的答案缩小到两位小数.所涉及的所有数学都必须保持两位小数的格式.我尝试了一些事情,我不知道要改变什么才能使这项工作成功.

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+"");
Run Code Online (Sandbox Code Playgroud)

Dam*_*ith 68

string.Format不会更改原始值,但会返回格式化的字符串.例如:

Console.WriteLine("Earnings this week: {0:0.00}", answer);
Run Code Online (Sandbox Code Playgroud)

注意:Console.WriteLine允许内联字符串格式化.以上相当于:

Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));
Run Code Online (Sandbox Code Playgroud)


Ehs*_*san 65

那么,根据您的需要,您可以选择以下任何一种.Out put是针对每种方法编写的

你可以选择你需要的那个

这将圆

decimal d = 2.5789m;
Console.WriteLine(d.ToString("#.##")); // 2.58
Run Code Online (Sandbox Code Playgroud)

这将确保写入2个小数位.

d = 2.5m;
Console.WriteLine(d.ToString("F")); //2.50
Run Code Online (Sandbox Code Playgroud)

如果你想写逗号,你可以使用它

d=23545789.5432m;
Console.WriteLine(d.ToString("n2")); //23,545,789.54
Run Code Online (Sandbox Code Playgroud)

如果要返回舍入的十进制值,可以执行此操作

d = 2.578m;
d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
Run Code Online (Sandbox Code Playgroud)

  • 投了反对票,因为这个例子使用了十进制,操作员询问的是双精度。 (2认同)

Kar*_*son 13

您可以将a舍入double到两个小数位,如下所示:

double c;
c = Math.Round(c, 2);
Run Code Online (Sandbox Code Playgroud)

但要注意四舍五入最终会咬你,所以谨慎使用它.

而是使用decimal数据类型.

  • 我确实尝试过Math.Round而且结果太快,结果变得无法实现. (2认同)

Kam*_*ely 11

    double d =  3.1493745;
    string s = $"{d:0.00}"; // or $"{d:#.##}"
    Console.WriteLine(s); // Displays 3.15
Run Code Online (Sandbox Code Playgroud)


anh*_*ppe 9

我会推荐定点("F")格式说明符(如Ehsan所述).请参阅标准数字格式字符串.

使用此选项,您甚至可以使用可配置的小数位数:

public string ValueAsString(double value, int decimalPlaces)
{
    return value.ToString($"F{decimalPlaces}");
}
Run Code Online (Sandbox Code Playgroud)