I have a follows code that i have run on LinqPad:
void Main()
{
List<VariableData> outputVariableData =
new List<VariableData>();
for(int i = 1 ; i< 100; i ++)
{
outputVariableData.Add(new VariableData
{
Id = i,
VariableValue = .33
});
}
double result = outputVariableData.Average(dd=> dd.VariableValue);
double add = outputVariableData.Sum(dd=> dd.VariableValue)/99;
add.Dump();
result.Dump();
}
public class VariableData
{
public int Id { get; set; }
public double VariableValue{ get; set; }
}
It results
0.329999999999999
0.329999999999999
When i check the average of same numbers in the excel sheet with formula =AVERAGE(A1:A101) and it return .33 as it is.
Actually i am drawing chart with this data and average value is showin on the chart, which making the chart drawing so absert and chart is not able to manage such type of value.
I am little confused about the output of these both, i suppose excel automatic round the value. so i have simple and little silly question that is output of my extension method is correct??
As noted, excel gives you a nice rounded version. For displaying of numbers this may be a very useful read: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
There is also http://msdn.microsoft.com/en-us/library/f5898377 available.
What’s the relevance of Standard Numeric Format Strings You Literally Ask?
Easy – the problem isn’t that the numbers wrong – it’s perfectly fine given the inaccuracies of floating point numbers. However displaying these numbers can be an issue – it’s not what we expect nor is it useful. However, if we spend a few seconds defining how we want our numbers presented…
Suddenly we get the output we want:
The problem now isn’t trying to massage the numbers to perfection, or using unusual datatype – but spending a few minutes figuring out what options are available and making use of them! It’s easy to do and very useful in the long run 🙂
Of course, this should only be used for displaying data – if you need to round data for computational reasons then I suggest looking into Math.Round etc.
Hope this answers your Q.
Supplemental:
This is another option that works in a very similar vein: http://msdn.microsoft.com/en-us/library/0c899ak8.aspx It explains how to do things like:
Which results in: