Home > Backend Development > C#.Net Tutorial > How to display up to 2 decimal places or simple integer using string format in C#?

How to display up to 2 decimal places or simple integer using string format in C#?

王林
Release: 2023-09-09 22:01:06
forward
1188 people have browsed it

如何在 C# 中使用字符串格式显示最多 2 位小数或简单整数?

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
Copy after login

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.

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();
   }
}
Copy after login

Output

123.00
Copy after login
Copy after login

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:

Example 2

class Program {
   static void Main(string[] args){
      int number = 123;
      var aNumberAsString = $"{number:0.00}";
      System.Console.WriteLine(aNumberAsString);
      Console.ReadLine();
   }
}
Copy after login

Output

123.00
Copy after login
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template