I have a string "10000.00", I would like to add commas in thousands place for a give string or number using C# .NET
String.Format()
? So I can show output as "1,00,00.00", something like this.
You can format currency in C# using various methods, here are few
decimal dec = 123.00M;
string ukCurrency = dec.ToString("C", new CultureInfo("en-GB")); // output -> "£123.00"
string usCurrency = dec.ToString("C", new CultureInfo("en-US")); // output -> "$123.00"
Here, "C" (or currency) format specifier converts a number to a string that represents a currency amount.
OR
double price = 1234.25;
string FormattedPrice = price.ToString("N");
//output
// 1,234.25
Here "N" is used instead of "C".
OR
var myPrice=110.1211;
Console.WriteLine(myPrice.ToString("C2")) ;
Console.WriteLine(myPrice.ToString("N2"));
//output
//$110.12
//110.12
The number after the C and N indicates upto how many decimals you need string formatted.
C formats the number as a currency string, which includes a currency symbol, default symbol is "$', you can use Culture Info as shown above for any other currency type.
OR
decimal CurrencyAmount = 1000.39m;
string moneyValue = String.Format("{0:C}", CurrencyAmount);
Console.WriteLine("Formatted value: "+ moneyValue);
//output :
//Formatted value: $1,000.39
OR
If your Currency value is not a decimal value
string.Format("{0:#.00}", Convert.ToDecimal(CurrencyValue) / 100);
Hope it helps.
I would like to add my own version here, if your string is in Decimal/Double, then you can format it in Currency as below
using System;
public class Program
{
public static void Main()
{
double amountInDouble = 1234.95;
amountInDouble.ToString("C");// formats based on local PC
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie"))); // €1,234.95
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es"))); // 1.234,95 €
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB"))); // £1,234.95
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au"))); // $1,234.95
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us"))); // $1,234.95
Console.WriteLine(amountInDouble.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca"))); // $1,234.95
}
}
Here is the fiddle link https://dotnetfiddle.net/YCPEwh
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly