54

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+"");
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Dan Cairnes
  • 551
  • 1
  • 4
  • 9
  • 2
    You probably don't want to be using floating-point for currency - the rounding errors bite you eventually. There doesn't seem to be anything built in, but see links like http://www.codeproject.com/Articles/28244/A-Money-type-for-the-CLR for inspiration. Having said that, when you start doing things like percentage calculations, you can't really avoid adding a few more decimal places... – canton7 Aug 24 '13 at 12:45
  • I need the doubles to always stay at two decimal places but the answer will not reflect this. so a format of: 209.00 (if you chose 1 product for product three and zero for all others this should be the answer.) – Dan Cairnes Aug 24 '13 at 12:45
  • And what answer are you getting? – Stobor Aug 24 '13 at 12:49
  • I was getting 108.9955, but now with Damith's code it works. – Dan Cairnes Aug 24 '13 at 12:53
  • 1
    Possible duplicate of [Using String Format to show decimal upto 2 places or simple integer](http://stackoverflow.com/questions/6951335/using-string-format-to-show-decimal-upto-2-places-or-simple-integer) – Sruit A.Suk Jan 13 '16 at 20:41

8 Answers8

86

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
Ehsan
  • 31,833
  • 6
  • 56
  • 65
85

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));
Metro Smurf
  • 37,266
  • 20
  • 108
  • 140
Damith
  • 62,401
  • 13
  • 102
  • 153
15

You can round a double to two decimal places like this:

double c;
c = Math.Round(c, 2);

But beware rounding will eventually bite you, so use it with caution.

Instead use the decimal data type.

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
13

I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.

With this option you can even have a configurable number of decimal places:

public string ValueAsString(double value, int decimalPlaces)
{
    return value.ToString($"F{decimalPlaces}");
}
John Cooling
  • 405
  • 4
  • 23
anhoppe
  • 4,287
  • 3
  • 46
  • 58
10
    double d =  3.1493745;
    string s = $"{d:0.00}"; // or $"{d:#.##}"
    Console.WriteLine(s); // Displays 3.15
Kamran Bigdely
  • 7,946
  • 18
  • 66
  • 86
3

Since you are working in currency why not simply do this:

Console.Writeline("Earnings this week: {0:c}", answer);

This will format answer as currency, so on my machine (UK) it will come out as:

Earnings this week: £209.00

Peter
  • 797
  • 11
  • 35
1

The problem is that when you are doing additions and multiplications of numbers all with two decimal places, you expect there will be no rounding errors, but remember the internal representation of double is in base 2, not in base 10 ! So a number like 0.1 in base 10 may be in base 2 : 0.101010101010110011... with an infinite number of decimals (the value stored in the double will be a number N with :

 0.1-Math.Pow(2,-64) < N < 0.1+Math.Pow(2,-64) 

As a consequence an operation like 12.3 + 0.1 may be not the same exact 64 bits double value as 12.4 (or 12.456 * 10 may be not the same as 124.56) because of rounding errors. For example if you store in a Database the result of 12.3 +0.1 into a table/column field of type double precision number and then SELECT WHERE xx=12.4 you may realize that you stored a number that is not exactly 12.4 and the Sql select will not return the record; So if you cannot use the decimal datatype (which has internal representation in base 10) and must use the 'double' datatype, you have to do some normalization after each addition or multiplication :

double freqMHz= freqkHz.MulRound(0.001); // freqkHz*0.001
double amountEuro= amountEuro.AddRound(delta); // amountEuro+delta


    public static double AddRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d+val));
    }
    public static double MulRound(this double d,double val)
    {
        return double.Parse(string.Format("{0:g14}", d*val));
    }
philoroussel
  • 111
  • 1
  • 3
0

If you want 0.5 instead of .5, use d.ToString("0.##").

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223