Monday, 25 March 2013

Effective Data Validation


Data Validation is a very important task to ensure discrepancies don’t creep-into when you make valuable information out of them.

Here, we’ll know how to ensure the correctness of data retrieved as strings that hold numbers in them.


Numbers can be in all sorts of format. Sometimes, numbers are allowed to have certain deviations from normal as exact correctness wouldn’t be the need of the hour. Hence validating numbers stored as strings can be quite tricky as there are many scenarios to be covered.

Specification of a threshold gives the numbers some slack to be present within a valid range. Let’s say we have 2 strings containing 2 numbers in them, say 124.954 and 124.955. You don’t mind the 2 numbers being precisely equal. Consider a threshold on 0.01 between them. As the absolute difference between the 2 numbers is only 0.001 (lesser than the threshold), the comparison between them results to be equal!

Please check out the 2 video links where I go through this topic in more detail.






The code typed-in during the tutorial is as follows for your reference:-
 
            //Matching Words
            //string s1 = "sand";
            //string s2 = "sand";

            //Mis-Matching Words
            //string s1 = "sand";
            //string s2 = "water";

            //Matching Doubles
            //string s1 = "124.954";
            //string s2 = "124.954";

            //Mis-Matching Doubles
            //string s1 = "125.654";
            //string s2 = "124.954";

            //Matching Doubles with trailing zeros
            //string s1 = "124.954";
            //string s2 = "124.954000";

            //Nearly matching doubles
            string s1 = "124.954";
            string s2 = "124.955";

            double d1 = 0.0;
            double d2 = 0.0;

            double threshold = 0.0001;

            var pass = new List<string>();
            var fail = new List<string>();

            if (double.TryParse(s1, out d1) && double.TryParse(s2, out d2))
            {
                //if (d1 == d2)
                if (Math.Abs(d1 - d2) <= threshold)
                    pass.Add(String.Join(" , ", s1, s2));
                else
                    fail.Add(String.Join(" , ", s1, s2));
            }
            else
            {
                if (s1 == s2)
                    pass.Add(String.Join(" , ", s1, s2));
                else
                    fail.Add(String.Join(" , ", s1, s2));
            }

Thank you for reading this post and watching the videos. Please Subscribe, Comment and Rate the channel if you liked the videos.

Goto C# Experiments to access more of such content! Thanks again!