0

C# code for formatting a number with commas and decimal

 public class Program
{
    public static void Main(string[] args)
    {
       string Str = null;
        Str =  string.Format(CultureInfo.InvariantCulture,"{0:c}", 9989.87);
Console.WriteLine(Str);
    }
}

Output is: $9,989.87 but i want as $ 9,989.87

  • [`string.Format(CultureInfo.InvariantCulture, "{0:N}", 9989.87)`](http://stackoverflow.com/questions/3360942/string-format-vs-tostring-and-using-invariantculture) – Slai Feb 09 '17 at 17:07
  • thanks Slai, it worked..instead of {0:N} if I use {0:C} then value is coming with currency also... but the problem is there is no space between currency and value .. How do I put space between them... I did like this Str = string.Format(CultureInfo.InvariantCulture, + " " + "{0:c}", 9989.87); but this is throwing error... – user7408807 Feb 09 '17 at 17:17

1 Answers1

0

To avoid some of the culture specific settings, you can try specifying the format:

string str = 9989.87.ToString("$ #,##0.00");  // or = $"{9989.87:$ #,##0.00}"; in VS 2015

or better

var str = "$ " + 9989.87.ToString("n", System.Globalization.CultureInfo.InvariantCulture);

Visual Studio 2015 interpolated string versions:

var str = System.FormattableString.Invariant($"$ {-9989.87:n}");    // "$ -9,989.87"

or with different formats for negative and zero values with the ; section separator:

var ss = $"{-9989.87:$ #,##0.00;-$ #,##0.00;-}";                    // "-$ 9,989.87"
Slai
  • 22,144
  • 5
  • 45
  • 53