- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use String Format to show decimal up to 2 places or simple integer in C#?
Converts the value of objects to strings based on the formats specified and inserts them into another string.
Namespace:System Assembly:System.Runtime.dll
Each overload of the Format method uses the composite formatting feature to include zero-based indexed placeholders, called format items, in a composite format string. At run time, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is null, the format item is replaced with String.Empty.
Example
class Program{ static void Main(string[] args){ int number = 123; var s = string.Format("{0:0.00}", number); System.Console.WriteLine(s); Console.ReadLine(); } }
Output
123.00
The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string. To identify a string literal as an interpolated string, prepend it with the $ symbol. You can embed any valid C# expression that returns a value in an interpolated string.
In the following example, as soon as an expression is evaluated, its result is converted into a string and included in a result string:
Example 2
class Program { static void Main(string[] args){ int number = 123; var aNumberAsString = $"{number:0.00}"; System.Console.WriteLine(aNumberAsString); Console.ReadLine(); } }
Output
123.00