Home  >  Article  >  Backend Development  >  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#?

王林
王林forward
2023-09-09 22:01:061137browse

如何在 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

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

Output

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:

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete