Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Fixed-Point ("F") Format Specifier
The Fixed-Point ("F") format specifier in C# converts a number to a string with a fixed number of decimal places. It produces output in the form "-ddd.ddd..." where "d" represents a digit (0-9). The negative sign appears only for negative numbers.
Syntax
Following is the syntax for using the Fixed-Point format specifier −
number.ToString("F") // Default 2 decimal places
number.ToString("Fn") // n decimal places (0-99)
number.ToString("F", culture) // With specific culture
Default Precision
When no precision is specified, the "F" format specifier defaults to 2 decimal places −
using System;
class Program {
static void Main() {
int value1 = 212;
double value2 = 45.7;
Console.WriteLine(value1.ToString("F"));
Console.WriteLine(value2.ToString("F"));
}
}
The output of the above code is −
212.00 45.70
Custom Precision
You can specify the exact number of decimal places using "Fn" where n is a number from 0 to 99 −
using System;
using System.Globalization;
class Program {
static void Main() {
int val1 = 38788;
int val2 = -344;
double val3 = 5656.789;
Console.WriteLine(val1.ToString("F", CultureInfo.InvariantCulture));
Console.WriteLine(val2.ToString("F3", CultureInfo.InvariantCulture));
Console.WriteLine(val3.ToString("F5", CultureInfo.InvariantCulture));
Console.WriteLine(val3.ToString("F0", CultureInfo.InvariantCulture));
}
}
The output of the above code is −
38788.00 -344.000 5656.78900 5657
Rounding Behavior
The Fixed-Point format specifier uses banker's rounding (round to nearest even) when the value needs to be rounded −
using System;
class Program {
static void Main() {
double value1 = 2.125;
double value2 = 2.135;
double value3 = 2.145;
Console.WriteLine($"{value1} -> {value1.ToString("F2")}");
Console.WriteLine($"{value2} -> {value2.ToString("F2")}");
Console.WriteLine($"{value3} -> {value3.ToString("F2")}");
}
}
The output of the above code is −
2.125 -> 2.12 2.135 -> 2.14 2.145 -> 2.14
Comparison with Other Format Specifiers
| Format | Description | Example (123.456) |
|---|---|---|
| F2 | Fixed-point with 2 decimals | 123.46 |
| N2 | Number with thousand separators | 123.46 |
| G | General format | 123.456 |
Conclusion
The Fixed-Point ("F") format specifier in C# provides precise control over decimal places in numeric output. It defaults to 2 decimal places but accepts custom precision from 0 to 99, making it ideal for financial calculations and formatted numeric displays where consistent decimal alignment is required.
