Erresen
Erresen

Reputation: 2043

mschart y-axis min / max setting issue (possible glitch?) C#

I have a problem with setting the maximum and minimum values for the y-axis of my mschart. When setting the max or min to a value, say 10.025, the value the chart sets as max is 10.024999618530273.

mainChart.ChartAreas[selectedChartArea].AxisY.Maximum = GetRoundYAxisMax(newYMax, newYRange);
mainChart.ChartAreas[selectedChartArea].AxisY.Minimum = GetRoundYAxisMin(newYMin, newYRange);

The GetRoundYAxisMax method just returns a "round" value. Code below.

private float GetRoundYAxisMax(double calculatedMax, double yAxisRange)
        {
            double rangeFactor = 0;

            if (yAxisRange > 10)
                rangeFactor = 1;
            else if (yAxisRange > 1)
                rangeFactor = 4;
            else if (yAxisRange > 0.1)
                rangeFactor = 40;
            else if (yAxisRange > 0.01)
                rangeFactor = 400;
            else if (yAxisRange > 0.001)
                rangeFactor = 4000;
            else if (yAxisRange > 0.0001)
                rangeFactor = 40000;
            else
                rangeFactor = 400000;

            float returnValue = (float)(Math.Round(calculatedMax * rangeFactor, MidpointRounding.ToEven) / rangeFactor);
            return returnValue;
        }

The rounding code evaluates properly and returns a correctly rounded value, but when setting this value to the max or min value on the y-axis it sets a value very close to it, but not rounded.

Any ideas why this is happening?

Upvotes: 0

Views: 2529

Answers (2)

David Davison
David Davison

Reputation: 1

Just answering why 10.024999618530273 rather than 10.025. Nothing on a computer is infinite in precision. You have ( IIRC ) 80 bits to represent your number. Part is exponent part is mantissa. What is happening is that 10.025 is not a number that has perfect representation in that number of bits. You dont get the whole number line, you get integral marks along it. ( take a random 80 bit double. That is a point on the number line. Now, add the smallest increment to that 80 bit double that is possible. Another point on the line. Now, in the "real" ( pun intended ) world, there are an infinite number of real points. Any point on the line you try to represent on a real world number line will be represented as one of the two points that bound that point in the 80 bit world ).

Upvotes: 0

Erresen
Erresen

Reputation: 2043

You can set the axis label style to round the un-rounded values: mainChart.ChartAreas[selectedChartArea].AxisY.LabelStyle.Format = "#.###";

Upvotes: 1

Related Questions