Monday, June 7, 2010

String Formatting in C#

Numbers

Basic number formatting specifiers:
Specifier Type Format Output (Passed Double 1.42) Output (Passed Int -12400)
c Currency {0:c} $1.42 -$12,400
d Decimal (Whole number) {0:d} System.FormatException -12400
e Scientific {0:e} 1.420000e+000 -1.240000e+004
f Fixed point {0:f} 1.42 -12400.00
g General {0:g} 1.42 -12400
n Number with commas for thousands {0:n} 1.42 -12,400
r Round trippable {0:r} 1.42 System.FormatException
x Hexadecimal {0:x4} System.FormatException cf90

Custom number formatting:
Specifier Type Example Output (Passed Double 1500.42) Note
0 Zero placeholder {0:00.0000} 1500.4200 Pads with zeroes.
# Digit placeholder {0:(#).##} (1500).42
. Decimal point {0:0.0} 1500.4
, Thousand separator {0:0,0} 1,500 Must be between two zeroes.
,. Number scaling {0:0,.} 2 Comma adjacent to Period scales by 1000.
% Percent {0:0%} 150042% Multiplies by 100, adds % sign.
e Exponent placeholder {0:00e+0} 15e+2 Many exponent formats available.
; Group separator see below

The group separator is especially useful for formatting currency values which require that negative values be enclosed in parentheses.

This table will help you to format the string value to double value:

Value           Format String              Result
1234.567     {0:0.00}                      1234.57
1234.567     {0:00000.0000}          01234.5670
1234.567     {0:#####.##}             1234.57
1234.567     {0:#.###}                   1234.567
1234.567     {0:#.#}                       1234.6
1234.567     {0:#,#.##}                  1,234.57
1234.567     {0:$#,#.##}                $1,234.57
1234.567     {0:$ #,#.##}               $ 1,234.57
1234.567     {0:($ #,#.##)}             ($ 1,234.57)
-1234.567    {0:#,#.##}                 -1,234.57
.1234           {0:#%}                       12%
.1234           {0:Percent = #.0%}     Percent = 12.3%

Example:
double dValue=1234.567;
string sCurrency =  dValue.ToString(" {0:0.00}",dValue);
Output: 1234.57

Or,
double dValue=23.00;
String.Format("{0:$#,##0.00;($#,##0.00);Zero}",dValue );
This will output “$1,240.00″ if passed 1243.50. It will output the same format but in parentheses if the number is negative, and will output the string “Zero” if the number is zero.

For more info: http://blog.stevex.net/string-formatting-in-csharp/

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...