Клубове Дир.бг
powered by diri.bg
търси в Клубове diri.bg Разширено търсене

Вход
Име
Парола

Клубове
Dir.bg
Взаимопомощ
Горещи теми
Компютри и Интернет
Контакти
Култура и изкуство
Мнения
Наука
Политика, Свят
Спорт
Техника
Градове
Религия и мистика
Фен клубове
Хоби, Развлечения
Общества
Я, архивите са живи
Клубове Дирене Регистрация Кой е тук Въпроси Списък Купувам / Продавам 03:35 17.05.24 
Клубове/ Компютри и Интернет / .NET Всички теми Следваща тема Пълен преглед*
Информация за клуба
Тема Re: Форматиращи стрингове [re: Borg]
Автор Любитeл (Лукав Благинар)
Публикувано29.10.04 13:54  



Ето ти извадки от MSDN-а (аз търсих String.Format method):
Standard numeric format strings are used to format common numeric types. A standard format string takes the form Axx where A is a single alphabetic character called the format specifier, and xx is an optional integer called the precision specifier. The format specifier must be one of the built-in format characters. The precision specifier ranges from 0 to 99 and controls the number of significant digits or zeros to the right of a decimal. The format string cannot contain white spaces.
If the format string does not contain one of the standard format specifiers, then a FormatException is thrown. For example, the format string "z" is interpreted as a standard numeric format string because it contains one alphabetic character, but the alphabetic character is not one of the standard numeric format specifiers so a FormatException is thrown. Any numeric format string that does not fit the definition of a standard numeric format string is interpreted as a custom numeric format string. The format string "c!" is interpreted as a custom format string because it contains two alphabetic characters, even though the character "c" is a standard numeric format specifier.
The following table describes the standard numeric format strings. Note that the result string produced by these format specifiers is influenced by the settings in the Regional Options control panel. Computers using different settings will generate different result strings.
Format specifierNameDescription
C or cCurrencyThe number is converted to a string that represents a currency amount. The conversion is controlled by the currency format information of the NumberFormatInfo object used to format the number. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default currency precision given by the NumberFormatInfo is used.
D or dDecimalThis format is supported for integral types only. The number is converted to a string of decimal digits (0-9), prefixed by a minus sign if the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
E or eScientific (exponential)The number is converted to a string of the form "-d.ddd...E+ddd" or "-d.ddd...e+ddd", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. One digit always precedes the decimal point. The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier is omitted, a default of six digits after the decimal point is used. The case of the format specifier indicates whether to prefix the exponent with an 'E' or an 'e'. The exponent always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet this minimum, if required.
F or fFixed-pointThe number is converted to a string of the form "-ddd.ddd..." where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
G or gGeneralThe number is converted to the most compact of either fixed-point or scientific notation, depending on the type of the number and whether a precision specifier is present. If the precision specifier is omitted or zero, the type of the number determines the default precision, as indicated by the following list.
Byte or SByte: 3
Int16 or UInt16: 5
Int32 or UInt32: 10
Int64 or UInt64: 19
Single: 7
Double: 15
Decimal: 29
Fixed-point notation is used if the exponent that would result from expressing the number in scientific notation is greater than -5 and less than the precision specifier; otherwise, scientific notation is used. The result contains a decimal point if required and trailing zeroes are omitted. If the precision specifier is present and the number of significant digits in the result exceeds the specified precision, then the excess trailing digits are removed by rounding. If scientific notation is used, the exponent in the result is prefixed with 'E' if the format specifier is 'G', or 'e' if the format specifier is 'g'.
The exception to the preceding rule is if the number is a Decimal and the precision specifier is omitted. In that case, fixed-point notation is always used and trailing zeroes are preserved.
N or nNumberThe number is converted to a string of the form "-d,ddd,ddd.ddd...", where each 'd' indicates a digit (0-9). The string starts with a minus sign if the number is negative. Thousand separators are inserted between each group of three digits to the left of the decimal point. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by the NumberFormatInfo is used.
P or pPercentThe number is converted to a string that represents a percent as defined by the NumberFormatInfo.PercentNegativePattern property or the NumberFormatInfo.PercentPositivePattern property. If the number is negative, the string produced is defined by the PercentNegativePattern and starts with a minus sign. The converted number is multiplied by 100 in order to be presented as a percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the default numeric precision given by NumberFormatInfo is used.
R or rRound-tripThe round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single. Although a precision specifier can be appended to the round-trip format specifier, it is ignored. Round trips are given precedence over precision when using this specifier. This format is supported by floating-point types only.
X or xHexadecimalThe number is converted to a string of hexadecimal digits. The case of the format specifier indicates whether to use uppercase or lowercase characters for the hexadecimal digits greater than 9. For example, use 'X' to produce "ABCDEF", and 'x' to produce "abcdef". The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier. This format is supported for integral types only.

The following example illustrates how to use the standard numeric format specifiers to format numeric base types.
[Visual Basic]
Imports System
Imports System.Globalization
Imports System.Threading

Module Module1
Sub Main()

Thread.CurrentThread.CurrentCulture = New CultureInfo("en-us")
Dim MyDouble As Double = 123456789

Console.WriteLine("The examples in en-US culture:")
Console.WriteLine(MyDouble.ToString("C"))
Console.WriteLine(MyDouble.ToString("E"))
Console.WriteLine(MyDouble.ToString("P"))
Console.WriteLine(MyDouble.ToString("N"))
Console.WriteLine(MyDouble.ToString("F"))

Thread.CurrentThread.CurrentCulture = New CultureInfo("de-DE")
Console.WriteLine("The examples in de-DE culture:")
Console.WriteLine(MyDouble.ToString("C"))
Console.WriteLine(MyDouble.ToString("E"))
Console.WriteLine(MyDouble.ToString("P"))
Console.WriteLine(MyDouble.ToString("N"))
Console.WriteLine(MyDouble.ToString("F"))
End Sub
End Module
[C#]
using System;
using System.Threading;
using System.Globalization;

class Class1
{
static void Main()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
double MyDouble = 123456789;

Console.WriteLine("The examples in en-US culture.\n");
Console.WriteLine(MyDouble.ToString("C"));
Console.WriteLine(MyDouble.ToString("E"));
Console.WriteLine(MyDouble.ToString("P"));
Console.WriteLine(MyDouble.ToString("N"));
Console.WriteLine(MyDouble.ToString("F"));

Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
Console.WriteLine("The examples in de-DE culture.\n");
Console.WriteLine(MyDouble.ToString("C"));
Console.WriteLine(MyDouble.ToString("E"));
Console.WriteLine(MyDouble.ToString("P"));
Console.WriteLine(MyDouble.ToString("N"));
Console.WriteLine(MyDouble.ToString("F"));
}
}
The preceding code example displays the following to the console.
The examples in en-US culture:
$123,456,789.00
1.234568E+008
12,345,678,900.00%
123,456,789.00
123456789.00
The examples in de-DE culture:
123.456.789,00 DM
1,234568E+008
12,345,678,900.00%
123.456.789,00
123456789,00
-----------------------------------------------------------------------------------------------------
If the standard numeric format specifiers do not provide the type of formatting you require, you can use custom format strings to further enhance string output. A standard format string consists of a single alphabetic character optionally followed by a sequence of digits that form a value between 0 and 99; all other format strings are custom format strings.
The following table shows the characters you can use to create custom numeric format strings and their definitions. Note that the result strings produced by some of these characters are influenced by the settings in the Regional Options control panel of the NumberFormatInfo object associated with the current thread. Computers using different cultures will generate different result strings.
Format characterNameDescription
0Zero placeholderIf the value being formatted has a digit in the position where the '0' appears in the format string, then that digit is copied to the result string. The position of the leftmost '0' before the decimal point and the rightmost '0' after the decimal point determines the range of digits that are always present in the result string. The "00" specifier causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "00" would result in the value 35.
#Digit placeholderIf the value being formatted has a digit in the position where the '#' appears in the format string, then that digit is copied to the result string. Otherwise, nothing is stored in that position in the result string. Note that this specifier never displays the '0' character if it is not a significant digit, even if '0' is the only digit in the string. It will display the '0' character if it is a significant digit in the number being displayed. The "##" format string causes the value to be rounded to the nearest digit preceding the decimal, where rounding away from zero is always used. For example, formatting 34.5 with "##" would result in the value 35.
.Decimal pointThe first '.' character in the format string determines the location of the decimal separator in the formatted value; any additional '.' characters are ignored. The actual character used as the decimal separator is determined by the NumberDecimalSeparator property of the NumberFormatInfo that controls formatting.
,Thousand separator and number scalingThe ',' character serves two purposes. First, if the format string contains a ',' character between two digit placeholders (0 or #) and to the left of the decimal point if one is present, then the output will have thousand separators inserted between each group of three digits to the left of the decimal separator. The actual character used as the decimal separator in the result string is determined by the NumberGroupSeparator property of the current NumberFormatInfo that controls formatting.
Second, if the format string contains one or more ',' characters immediately to the left of the decimal point, then the number will be divided by the number of ',' characters multiplied by 1000 before it is formatted. For example, the format string "0,," will represent 100 million as simply 100. Use of the ',' character to indicate scaling does not include thousand separators in the formatted number. Thus, to scale a number by 1 million and insert thousand separators you would use the format string "#,##0,,".
%Percentage placeholderThe presence of a '%' character in a format string causes a number to be multiplied by 100 before it is formatted. The appropriate symbol is inserted in the number itself at the location where the '%' appears in the format string. The percent character used is dependent on the current NumberFormatInfo class.
E0
E+0
E-0
e0
e+0
e-0Scientific notationIf any of the strings "E", "E+", "E-", "e", "e+", or "e-" are present in the format string and are followed immediately by at least one '0' character, then the number is formatted using scientific notation with an 'E' or 'e' inserted between the number and the exponent. The number of '0' characters following the scientific notation indicator determines the minimum number of digits to output for the exponent. The "E+" and "e+" formats indicate that a sign character (plus or minus) should always precede the exponent. The "E", "E-", "e", or "e-" formats indicate that a sign character should only precede negative exponents.
\Escape characterIn C# and the Managed Extensions for C++, the backslash character causes the next character in the format string to be interpreted as an escape sequence. It is used with traditional formatting sequences like '\n' (new line).
In some languages, the escape character itself must be preceded by an escape character when used as a literal. Otherwise, the compiler interprets the character as an escape sequence. Use the string "\\" to display '\'.
Note that this escape character is not supported in Visual Basic; however, ControlChars provides the same functionality.
'ABC'
"ABC"Literal stringCharacters enclosed in single or double quotes are copied to the result string literally, and do not affect formatting.
;Section separatorThe ';' character is used to separate sections for positive, negative, and zero numbers in the format string.
OtherAll other charactersAll other characters are copied to the result string as literals in the position they appear.

Note that for fixed-point format strings (strings not containing an "E0", "E+0", "E-0", "e0", "e+0", or "e-0"), numbers are rounded to as many decimal places as there are digit placeholders to the right of the decimal point. If the format string does not contain a decimal point, the number is rounded to the nearest integer. If the number has more digits than there are digit placeholders to the left of the decimal point, the extra digits are copied to the result string immediately before the first digit placeholder.
Different formatting can be applied to a string based on whether the value is positive, negative, or zero. To produce this behavior, a custom format string can contain up to three sections separated by semicolons:
One section: The format string applies to all values.
Two sections: The first section applies to positive values and zeros, and the second section applies to negative values. If the number to be formatted is negative, but becomes zero after rounding according to the format in the second section, then the resulting zero is formatted according to the first section.
Three sections: The first section applies to positive values, the second section applies to negative values, and the third section applies to zeros. The second section might be left empty (by having nothing between the semicolons), in which case the first section applies to all nonzero values. If the number to be formatted is nonzero, but becomes zero after rounding according to the format in the first or second section, then the resulting zero is formatted according to the third section.
This type of formatting ignores any preexisting formatting associated with a number when the final value is formatted. For example, negative values are always displayed without a minus sign when section separators are used. If you want the final formatted value to have a minus sign, you should explicitly include the minus sign as part of the custom format specifier. The following example illustrates how section separators can be used to produce formatted strings.
[Visual Basic]
Dim MyPos As Double = 19.95

Dim MyNeg As Double = -19.95

Dim MyZero As Double = 0

Dim MyString As String = MyPos.ToString("$#,##0.00;($#,##0.00);Zero")

' In the U.S. English culture, MyString has the value: $19.95.

MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero")

' In the U.S. English culture, MyString has the value: ($19.95).
' The minus sign is omitted by default.

MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero")

' In the U.S. English culture, MyString has the value: Zero.
[C#]
double MyPos = 19.95, MyNeg = -19.95, MyZero = 0.0;

string MyString = MyPos.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: $19.95.

MyString = MyNeg.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: ($19.95).
// The minus sign is omitted by default.

MyString = MyZero.ToString("$#,##0.00;($#,##0.00);Zero");

// In the U.S. English culture, MyString has the value: Zero.
The following example demonstrates custom number formatting.
[Visual Basic]
Dim myDouble As Double = 1234567890
Dim myString As String = myDouble.ToString( "(###) ### - ####" )
' The value of myString is "(123) 456 – 7890".

Dim MyInt As Integer = 42
MyString = MyInt.ToString( "My Number " + ControlChars.Lf + "= #" )
' In the U.S. English culture, MyString has the value:
' "My Number
' = 42".
[C#]
Double myDouble = 1234567890;
String myString = myDouble.ToString( "(###) ### - ####" );
// The value of myString is "(123) 456 – 7890".

int MyInt = 42;
MyString = MyInt.ToString( "My Number \n= #" );
// In the U.S. English culture, MyString has the value:
// "My Number
// = 42".



Цялата тема
ТемаАвторПубликувано
* Форматиращи стрингове Borg   29.10.04 11:34
. * Re: Форматиращи стрингове Любитeл   29.10.04 13:54
. * Re: Форматиращи стрингове NetDev   29.10.04 13:55
. * Re: Форматиращи стрингове Borg   29.10.04 15:13
Клуб :  


Clubs.dir.bg е форум за дискусии. Dir.bg не носи отговорност за съдържанието и достоверността на публикуваните в дискусиите материали.

Никаква част от съдържанието на тази страница не може да бъде репродуцирана, записвана или предавана под каквато и да е форма или по какъвто и да е повод без писменото съгласие на Dir.bg
За Забележки, коментари и предложения ползвайте формата за Обратна връзка | Мобилна версия | Потребителско споразумение
© 2006-2024 Dir.bg Всички права запазени.