0

I have seen plenty of questions on how to round to two decimal places using Math.Round(), but not when using placeholders. This is my best attempt but the program is still giving me around 14 decimal places:

Console.Write("\n\nPercentatge Weight: {0}% ", 
    G[ArrayCount] * 100 / RayTotal,
    Math.Round(RayTotal, 2));

After this runs I am getting a percentage such as 14.3256941565.

I just want it to be 14.33

Should add that I don't already have the value it is dependent on what the user enters.

gunr2171
  • 16,104
  • 25
  • 61
  • 88
BigGizzy
  • 17
  • 1
  • 5
  • Your syntax for the `Console.Write({0}, arg)` is off. You have two args but only have `{0}` in your write statement. – tyh Nov 18 '13 at 22:43

3 Answers3

2

The placeholder {0} refers to the first argument, but your rounded value is the second argument.

To format it with the placeholder only, you would need to include the F2 specified, where 2 is the number of decimal places:

Console.Write("\n\nPercentatge Weight: {0:F2}% ", G[ArrayCount] * 100 / RayTotal);

Further info in MSDN here.

mezoid
  • 28,090
  • 37
  • 107
  • 148
Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
2

If you already have your number as a percentage, you can use f2 as a format string to round to the 2 decimal places:

double myDouble = 14.3256941565;
Console.WriteLine("Percentage Weight: {0:f2}%", myDouble); // Percentage Weight: 14.33%

Otherwise you can use p2 as a format string to automatically format the number as a percentage:

double myDouble = 0.143256941565;
Console.WriteLine("Percentage Weight: {0:p2}", myDouble); // Percentage Weight: 14.33 %

Further Reading

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0
   double myDouble = 14.3256941565;

   Console.WriteLine("Percentage Weight: {0}%", Math.Round(myDouble, 2));
BRAHIM Kamel
  • 13,492
  • 1
  • 36
  • 47