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
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));
}