Thursday, December 21, 2017

WinForms TextBox Get as Double or Integer

I always end up returning to Windows Forms when I want to code some tool or prototype an idea. This time I just want to share two extension methods for retrieving the contents of a TextBox as an Integer or a Double.

public static double AsDouble(this TextBox textBox)
{
 var s = textBox.Text.Replace(",", ".").Trim();
 return double.TryParse(s, out var d) ? d : double.NaN;
}
public static int AsInt(this TextBox textBox)
{
 var s = textBox.Text.Trim();
 return int.TryParse(s, out var i) ? i : 0;
}

The colon to period replacement is to ensure that Swedish formatting works with the default parser. No guarantee that it will work with all cultures.


All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!

Thursday, December 7, 2017

Asserting floating point values in unit tests


Just a few methods to help out with unit testing, mainly for asserting floating point values (float, double) to be within a tolerance of the expected value

public static class Dessert
{
    public static void AreEqual(double expected, double actual, double tolerance)
    {
        Assert.IsTrue(expected.IsEqual(actual, tolerance),
            $"{Environment.NewLine}Dessert.AreEqual(double, double) failed. Expected:<{expected}>. Actual<{actual}>. Tolerance<{tolerance}>");
    }
        
    public static void AreEqual(float expected, float actual, float tolerance)
    {
        Assert.IsTrue(expected.IsEqual(actual, tolerance),
            $"{Environment.NewLine}Dessert.AreEqual(float, float) failed. Expected:<{expected}>. Actual<{actual}>. Tolerance<{tolerance}>");
    }
}

How to use:

Dessert.AreEqual(2700, weight, 0.000000000000001);

All code provided as-is. This is copied from my own code-base, May need some additional programming to work. Use for whatever you want, how you want! If you find this helpful, please leave a comment, not required but appreciated! :)

Hope this helps someone out there!