Conversion and Dates

Rounding numbers

Math.Round standard uses midpoint rounding to even (Banker's rounding) instead of rounding away from zero.
More info about midpoint rounding
Microsoft about midpoint rounding
So normally you should use Math.Round(number, decimals, MidpointRounding.AwayFromZero).
The problem is this doesn't work anymore with numbers > 1024.
Instead, use decimal.Round(number, decimals, MidpointRouding.AwayFromZero). This works.

Mind that converting to an integer will truncate instead of round.
So (int)432.83 gives 432 instead of 433!

Showing numbers

.ToString(format, numberSettings)
format: string e.g. "#0.00"
numberSettings: System.Globalization.NumberFormatInfo
numberSettings = (System.Globalization.NumberFormatInfo)System.Globalization.CultureInfo.CurrentCulture.NumberFormat.Clone();
numberSettings.NumberDecimalSeparator = ",";

Convert versus .Parse

.Parse only converts from a string, Convert.ToInt can take several types of parameters.
Convert.ToInt(null) returns 0, integer.Parse(null) gives an error.
Both Convert.ToInt("") and integer.Parse("") give an error.
You can solve this with:
string.IsNullOrEmpty(string) ? 0 : decimal.Parse(string)
To avoid errors, use .TryParse

Decimal.Parse(…, CultureInfo.CurrentCulture): will also process decimals with the current decimal separator.

.TryParse

Boolean result = DateTime.TryParse(string date, out DateTime date)
Result = true when parse succeeded.
decimal.TryParse(string, NumberStyles.Integer/.Number, numberSettings, out decimalvalue) // numberSettings: see Showing numbers

Conversion of dates in a certain format

DateTime.TryParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDate)

Adding and subtracting date/time values

Use .AddYears, .AddMonths …

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License