C#使用ToString格式化
示例
通常我们使用的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"
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便