Search This Blog

Showing posts with label Convert. Show all posts
Showing posts with label Convert. Show all posts

Sunday, August 12, 2018

Properly handle insertion of values of type Double into database, independently of CurrentCulture, in C#

if (row[column] is double)
{
    //properly deal with rational numbers - ALWAYS use the same (english - culture invariant) numbering format rules - otherwise data will differ between cultures
    //for example, portuguese uses , as thousand separator, while english uses a dot. This causes mySql to calculate different values form SUM(myColumn).

    var d = Convert.ToDouble(row[column]);
    value = d.ToString(CultureInfo.InvariantCulture);
}

Monday, August 1, 2016

.NET's built in methods to convert between distinct numeric representations (supports 2, 8, 10 and 16 only)

Here's something that few seem to know about, but that more than often we are in need of: the .NET's Convert methods can convert to/from the following numeric representations 2, 8, 10, 16.

            var binary = Convert.ToString(30, 2); // 11110
            var bits = binary.ToCharArray().Select(c => byte.Parse(c.ToString())); // a collection of the bits stored in 'binary' above
            var hexa = Convert.ToString(100, 16); //64
            var octa = Convert.ToInt64(12.ToString(), 8); //10 (decimal representation of 12 in base 8 = 10)