Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 12: String.Format

Parameter

Details

format

args

provider

A composite format string, which defines the way args should be combined into a string.

A sequence of objects to be combined into a string. Since this uses a params argument, you can either use a comma-separated list of arguments or an actual object array.

A collection of ways of formatting objects to strings. Typical values include CultureInfo.InvariantCulture and CultureInfo.CurrentCulture.

The Format methods are a set of overloads in the System.String class used to create strings that combine objects

into specific string representations. This information can be applied to String.Format, various WriteLine methods as well as other methods in the .NET framework.

Section 12.1: Since C# 6.0

Version ≥ 6.0

Since C# 6.0 it is possible to use string interpolation in place of String.Format.

string name = "John"; string lastname = "Doe";

Console.WriteLine($"Hello {name} {lastname}!");

Hello John Doe!

More examples for this under the topic C# 6.0 features: String interpolation.

Section 12.2: Places where String.Format is 'embedded' in the framework

There are several places where you can use String.Format indirectly: The secret is to look for the overload with the signature string format, params object[] args, e.g.:

Console.WriteLine(String.Format("{0} - {1}", name, value));

Can be replaced with shorter version:

Console.WriteLine("{0} - {1}", name, value);

There are other methods which also use String.Formate.g.:

Debug.WriteLine(); // and Print()

StringBuilder.AppendFormat();

Section 12.3: Create a custom format provider

public class CustomFormat : IFormatProvider, ICustomFormatter

{

public string Format(string format, object arg, IFormatProvider formatProvider)

{

if (!this.Equals(formatProvider))

GoalKicker.com – C# Notes for Professionals

62

{

return null;

}

if (format == "Reverse")

{

return String.Join("", arg.ToString().Reverse());

}

return arg.ToString();

}

public object GetFormat(Type formatType)

{

return formatType==typeof(ICustomFormatter) ? this:null;

}

}

Usage:

String.Format(new CustomFormat(), "-> {0:Reverse} <-", "Hello World");

Output:

-> dlroW olleH <-

Section 12.4: Date Formatting

DateTime date = new DateTime(2016, 07, 06, 18, 30, 14);

// Format: year, month, day hours, minutes, seconds

Console.Write(String.Format("{0:dd}",date));

//Format by Culture info

String.Format(new System.Globalization.CultureInfo("mn-MN"),"{0:dddd}",date);

Version ≥ 6.0

Console.Write($"{date:ddd}");

output :

06

Лхагва

06

Specifier

Meaning

Sample

 

Result

d

Date

 

 

 

 

 

 

 

 

 

7/6/2016

{

:d}

0

dd

Day, zero-padded

 

 

 

 

 

 

 

 

06

{

:dd}

0

ddd

Short day name

 

 

 

 

 

 

 

 

Wed

{

:ddd}

0

dddd

Full day name

 

 

 

 

 

 

 

Wednesday

{

:dddd}

0

D

Long date

 

 

 

 

 

 

 

 

Wednesday, July 6, 2016

{

:D}

0

f

Full date and time, short

 

 

 

 

 

 

 

Wednesday, July 6, 2016 6:30 PM

{

:f}

0

 

Second fractions, 2 digits

 

 

 

 

 

20

{

:ff}

0

f

Second fractions, 3 digits

 

 

 

201

{

:fff}

0

 

Second fractions, 4 digits

 

 

 

2016

{

:ffff}

0

F

Full date and time, long

 

 

 

 

 

Wednesday, July 6, 2016 6:30:14 PM

{

:F}

 

0

 

GoalKicker.com – C# Notes for Professionals

63

g

Default date and time

 

 

 

 

 

 

7/6/2016 6:30 PM

{

0

:g}

gg

Era

 

 

 

 

 

A.D

{

:gg}

0

hh

Hour (2 digits, 12H)

 

 

 

 

 

06

{

:hh}

0

HH

Hour (2 digits, 24H)

 

 

 

 

 

18

{

:HH}

0

M

Month and day

 

 

 

 

 

July 6

{

:M}

0

mm

Minutes, zero-padded

 

 

 

 

 

30

{

:mm}

0

MM

Month, zero-padded

 

 

 

 

 

07

{

:MM}

0

MMM

3-letter month name

 

 

 

Jul

{

:MMM}

0

MMMM

Full month name

 

 

 

July

{

:MMMM}

0

ss

Seconds

 

 

 

 

14

{

:ss}

0

r

RFC1123 date

 

 

 

 

Wed, 06 Jul 2016 18:30:14 GMT

{

:r}

0

s

Sortable date string

 

 

 

 

2016-07-06T18:30:14

{

:s}

0

t

Short time

 

 

 

 

6:30 PM

{

:t}

0

T

Long time

 

 

 

 

6:30:14 PM

{

:T}

0

tt

AM/PM

 

 

 

PM

{

:tt}

0

u

Universal sortable local time

 

 

 

 

2016-07-06 18:30:14Z

{

:u}

0

U

Universal GMT

 

 

 

 

Wednesday, July 6, 2016 9:30:14 AM

{

:U}

0

Y

Month and year

 

 

 

 

July 2016

{

:Y}

0

yy

2 digit year

 

 

 

 

16

{

:yy}

0

yyyy

4 digit year

 

 

 

2016

{

:yyyy}

0

zz

2 digit timezone o set

 

 

 

 

+09

{

:zz}

0

zzz

full time zone o set

 

 

 

 

+09:00

{

:zzz}

0

Section 12.5: Currency Formatting

The "c" (or currency) format specifier converts a number to a string that represents a currency amount. string.Format("{0:c}", 112.236677) // $112.23 - defaults to system

Precision

Default is 2. Use c1, c2, c3 and so on to control precision.

string.Format("{0:C1}", 112.236677) //$112.2 string.Format("{0:C3}", 112.236677) //$112.237 string.Format("{0:C4}", 112.236677) //$112.2367 string.Format("{0:C9}", 112.236677) //$112.236677000

Currency Symbol

1. Pass CultureInfo instance to use custom culture symbol.

string.Format(new CultureInfo("en-US"), "{0:c}", 112.236677); //$112.24 string.Format(new CultureInfo("de-DE"), "{0:c}", 112.236677); //112,24 string.Format(new CultureInfo("hi-IN"), "{0:c}", 112.236677); // 112.24

2. Use any string as currency symbol. Use NumberFormatInfo as to customize currency symbol.

NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; nfi = (NumberFormatInfo) nfi.Clone();

nfi.CurrencySymbol = "?";

GoalKicker.com – C# Notes for Professionals

64

string.Format(nfi, "{0:C}", 112.236677); //?112.24 nfi.CurrencySymbol = "?%^&";

string.Format(nfi, "{0:C}", 112.236677); //?%^&112.24

Position of Currency Symbol

Use CurrencyPositivePattern for positive values and CurrencyNegativePattern for negative values.

NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; nfi.CurrencyPositivePattern = 0;

string.Format(nfi, "{0:C}", 112.236677); //$112.24 - default nfi.CurrencyPositivePattern = 1;

string.Format(nfi, "{0:C}", 112.236677); //112.24$ nfi.CurrencyPositivePattern = 2; string.Format(nfi, "{0:C}", 112.236677); //$ 112.24 nfi.CurrencyPositivePattern = 3; string.Format(nfi, "{0:C}", 112.236677); //112.24 $

Negative pattern usage is the same as positive pattern. A lot more use cases please refer to original link.

Custom Decimal Separator

NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat; nfi.CurrencyPositivePattern = 0;

nfi.CurrencyDecimalSeparator = ".."; string.Format(nfi, "{0:C}", 112.236677); //$112..24

Section 12.6: Using custom number format

NumberFormatInfo can be used for formatting both integer and float numbers.

// invariantResult is "1,234,567.89"

var invarianResult = string.Format(CultureInfo.InvariantCulture, "{0:#,###,##}", 1234567.89);

//NumberFormatInfo is one of classes that implement IFormatProvider var customProvider = new NumberFormatInfo

{

NumberDecimalSeparator = "_NS_", // will be used instead of ',' NumberGroupSeparator = "_GS_", // will be used instead of '.'

};

//customResult is "1_GS_234_GS_567_NS_89"

var customResult = string.Format(customProvider, "{0:#,###.##}", 1234567.89);

Section 12.7: Align left/ right, pad with spaces

The second value in the curly braces dictates the length of the replacement string. By adjusting the second value to be positive or negative, the alignment of the string can be changed.

string.Format("LEFT: string: ->{0,-5}<- int: ->{1,-5}<-", "abc", 123); string.Format("RIGHT: string: ->{0,5}<- int: ->{1,5}<-", "abc", 123);

Output:

LEFT: string: ->abc <- int: ->123 <-

RIGHT: string: -> abc<- int: -> 123<-

GoalKicker.com – C# Notes for Professionals

65