I have been trying to make the answer this prints out to be to two decimal places. All the math involved has to stay at that format of two decimal places. I have tried a few things and I am not sure what to change to make this work.
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+"");
1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.
string.Format
will not change the original value, but it will return a formatted string. For example:
Console.WriteLine("Earnings this week: {0:0.00}", answer);
Note: Console.WriteLine
allows inline string formatting. The above is equivalent to:
Console.WriteLine("Earnings this week: " + string.Format("{0:0.00}", answer));
Well, depending on your needs you can choose any of the following. Out put is written against each method
You can choose the one you need
This will round
decimal d = 2.5789m; Console.WriteLine(d.ToString("#.##")); // 2.58
This will ensure that 2 decimal places are written.
d = 2.5m; Console.WriteLine(d.ToString("F")); //2.50
if you want to write commas you can use this
d=23545789.5432m; Console.WriteLine(d.ToString("n2")); //23,545,789.54
if you want to return the rounded of decimal value you can do this
d = 2.578m; d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With