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 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练