Home > Article > Backend Development > How to display up to 2 decimal places or simple integer using string format in C#?
Converts the object's values to a string according to the specified format and inserts them into another string.
Namespace:System Assembly:System.Runtime.dll
Each overload of the Format method uses the compound formatting functionality to include zero-based indexed placeholders (called format items) in the compound format string. At run time, each format item is replaced by the string representation of the corresponding parameter in the parameter list. If the parameter value is null, the format item is replaced with String.Empty.
class Program{ static void Main(string[] args){ int number = 123; var s = string.Format("{0:0.00}", number); System.Console.WriteLine(s); Console.ReadLine(); } }
123.00
The string interpolation function builds on the compound formatting function and provides a more readable and convenient syntax for formatting The expression result is included in the result string. To identify a string literal as an interpolated string, precede it with a $ sign. You can embed any valid C# expression that returns a value in an interpolated string.
In the following example, once the expression is evaluated, its result is converted to a string and included in the result string:
class Program { static void Main(string[] args){ int number = 123; var aNumberAsString = $"{number:0.00}"; System.Console.WriteLine(aNumberAsString); Console.ReadLine(); } }
123.00
The above is the detailed content of How to display up to 2 decimal places or simple integer using string format in C#?. For more information, please follow other related articles on the PHP Chinese website!