Reputation: 9396
The current culture is "fr-FR" (already set in the application)
decimal amount = 20m;
var formattedCurrency = string.Format(Thread.CurrentThread.CurrentCulture, "{0:C}", amount);
It gives me 20,00 €
how to remove the trailing zeroes?
EDIT:
I tried using G29
to remove trailing zeroes, but lost the currency symbol. :(
Upvotes: 1
Views: 1867
Reputation: 862
try this one https://dotnetfiddle.net/F3cJmu
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
double amount = 39.5555;
string decimalPoint = (amount).ToString();
decimalPoint = decimalPoint.Substring(decimalPoint.IndexOf(".") + 1);
if( decimalPoint.Length > 0)
Console.WriteLine(string.Format(new CultureInfo("en-US"),"{0:C" + decimalPoint.Length +"}", amount));
else
Console.WriteLine(string.Format(new CultureInfo("en-US"),"{0:C}", amount));
}
}
Upvotes: 1
Reputation: 1175
double dec = 20.01;
string amount = string.Format("{0:#.##}", dec);
switch (CultureInfo.CurrentCulture.NumberFormat.CurrencyPositivePattern)
{
case 0:
amount = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + amount;
break;
case 1:
amount = amount + CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
break;
case 2:
amount = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol + " " + amount;
break;
case 3:
amount = amount + " " + CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;
break;
}
Updated after Davio's comment
Regards.
Upvotes: 1
Reputation: 4737
This will work:
string.Format(Thread.CurrentThread.CurrentCulture, "{0:#.##}", amount) + " " + Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencySymbol
If you need to know where the currency symbol should appear, it becomes a bit more complex, but this could be sufficient (depending on your situation).
The thing is, you can't specify conditional digits for a currency format and there are good reasons you shouldn't!
The thing is: 20
loses significant digits over 20.00
, so the customer doesn't know whether it's 20.01
rounded down or 20.00
rounded down. I would use {0:C}
unless I have a very good reason not to.
Upvotes: 1