Formatting using ToString
suggest changeString.Format is one way to format values. ToString can take the same kind of format string and return the formatted text directly. Month and day names, and the decimal separator, follow the current culture. The DateTime comments below assume 21 July 2016, 7:23:15 PM local time, formatted with an English culture.
Integer to formatted string:
int intValue = 10;
string zeroPaddedInteger = intValue.ToString("000"); // Output will be "010"
string customFormat = intValue.ToString("Input value is 0"); // output will be "Input value is 10"
double to formatted string:
double doubleValue = 10.456;
string roundedDouble = doubleValue.ToString("0.00"); // output 10.46
string integerPart = doubleValue.ToString("00"); // output 10
string customFormat = doubleValue.ToString("Input value is 0.0"); // Input value is 10.5
Formatting DateTime using ToString
DateTime currentDate = DateTime.Now; // {7/21/2016 7:23:15 PM}
string dateTimeString = currentDate.ToString("dd-MM-yyyy HH:mm:ss"); // "21-07-2016 19:23:15"
string dateOnlyString = currentDate.ToString("dd-MM-yyyy"); // "21-07-2016"
string dateWithMonthInWords = currentDate.ToString("dd-MMMM-yyyy HH:mm:ss"); // "21-July-2016 19:23:15"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents