简体   繁体   中英

Format a decimal with currency symbol and no trailing zeroes?

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?

  1. Note: If the amount is 20.01, then the output should be 20,01 €
  2. If the amount is 20.00, then the output should be 20 €

EDIT:

I tried using G29 to remove trailing zeroes, but lost the currency symbol. :(

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.

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

}
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM