通常我们使用的String.Format是格式化方法,.ToString通常用于将其他类型转换为字符串。我们可以在进行转换时指定格式以及ToString方法,这样就可以避免额外的格式化。让我解释一下它如何与不同类型一起使用;
整数到格式化的字符串:
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 doubleValue = 10.456;
string roundedDouble = doubleValue.ToString("0.00"); // 输出10.46
string integerPart = doubleValue.ToString("00"); // 输出10
string customFormat = doubleValue.ToString("Input value is 0.0"); // 输入值为10.5使用ToString格式化DateTime
DateTime currentDate = DateTime.Now; // {2016/7/21下午7:23:15}
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"