Print number with commas as 1000 separators in C#

CsharpProgrammingServer Side Programming

Firstly, set the number as string −

string num = "1000000.8765";

Now, work around differently for number before and after the decimal −

string withoutDecimals = num.Substring(0, num.IndexOf("."));
string withDecimals = num.Substring(num.IndexOf("."));

Use the ToString() method to set the format for 1000 separators −

ToString("#,##0")

The following is the complete code to display number with commas as 1000 separators −

Example

 Live Demo

using System;
public class Program {
   public static void Main() {
      string num = "1000000.8765";
      string withoutDecimals = num.Substring(0, num.IndexOf("."));
      string withDecimals = num.Substring(num.IndexOf("."));
      withoutDecimals = Convert.ToInt32(withoutDecimals).ToString("#,##0");
      Console.WriteLine(withoutDecimals + withDecimals);
   }
}

Output

1,000,000.8765
raja
Published on 31-Aug-2018 12:03:39
Advertisements