C# General ("G") Format Specifier
Description
The general ("G") specifier formats a number 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.
Item | Value |
---|---|
Format specifier | "G" or "g" |
Supported by | All numeric types. |
Result | The most compact of either fixed-point or scientific notation. |
Precision specifier | defines the maximum number of significant digits that can appear in the result string. |
Default precision specifier | Depends on numeric type. |
Examples,
Value | Format | Formatted |
---|---|---|
-123.456 | ("G", en-US) | -123.456 |
123.456 | ("G", sv-SE) | -123,456 |
123.4546 | ("G4", en-US) | 123.5 |
123.4546 | ("G4", sv-SE) | 123,5 |
-1.234567890e-25 | ("G", en-US) | -1.23456789E-25 |
-1.234567890e-25 | ("G", sv-SE) | -1,23456789E-25 |
The default precision is listed in the following table.
Numeric type | Default precision |
---|---|
Byte or SByte | 3 digits |
Int16 or UInt16 | 5 digits |
Int32 or UInt32 | 10 digits |
Int64 | 19 digits |
UInt64 | 20 digits |
BigInteger | 50 digits |
Single | 7 digits |
Double | 15 digits |
Decimal | 29 digits |
The result string is affected by the following NumberFormatInfo
properties.
- NegativeSign
- NumberDecimalSeparator
- PositiveSign
Example
using System;//w w w.java2 s. co m
using System.Globalization;
class MainClass
{
static void Main()
{
double number;
number = 12345.6789;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 12345.6789
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 12345,6789
Console.WriteLine(number.ToString("G7", CultureInfo.InvariantCulture));
// Displays 12345.68
}
}
The code above generates the following result.
Scientific format
using System;/* w w w . j a va2 s .c o m*/
using System.Globalization;
class MainClass
{
static void Main()
{
double number = .0000023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 2.3E-06
Console.WriteLine(number.ToString("G",
CultureInfo.CreateSpecificCulture("fr-FR")));
// Displays 2,3E-06
number = .0023;
Console.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));
// Displays 0.0023
number = 1234;
Console.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));
// Displays 1.2E+03
number = Math.PI;
Console.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));
// Displays 3.1416
}
}
The code above generates the following result.