简体   繁体   中英

decimal to string conversion in C#

How can I convert a list of decimal values to strings such that:

  • No decimal point is shown if the value is an integer
  • Otherwise, the number is formatted to a minimum of two decimal places

For example:

var items = new List<decimal>
{
    120.5,
    110,
    25.356
};

foreach (var item in items)
{
    var itemString = item.ToString();
}

This should result in the following string values:

"120.50"
"110"
"25.356"

You can use the decimal.ToString override to specify a formatting.

decimal amount = 120.5m;
string str = amount.ToString("0.00");

This can also be used when using String.Format.

Console.WriteLine("{0:0.00}", amount); 

In the case of your first and second rule, it cannot be done on one line.

decimal amount = 120.5m;
string str = amount.ToString("0.00").Replace(".00", String.Empty);

The following extension method should satisfy you requirements. The comments on the code was provided in OP and comments.

public static string ToFormattedString(this decimal d)
{
    //The comma is not mandatory. but 
    var s = d.ToString();
    var tokens = s.Split(new[]{"."}, StringSplitOptions.RemoveEmptyEntries);
    //if there are no decimal points 12 then there should no be any zeros and periods (.)
    if (tokens.Length == 1)
        return s;
    //I need to remove trailing zeros
    var places = tokens[1].TrimEnd('0');
    if (places.Length == 0)
        return tokens[0];
    //if there is only one decimal point ex- 0.5 then it should be displayed as 0.50 
    if (places.Length == 1)
        return d.ToString("F2");
    var format = string.Format("F{0}", places.Length);
    return d.ToString(format);
}

Used like this

var x = new decimal[]{120.5m, 110, 25.356m};
foreach (var item in x)
    Console.WriteLine("{0} => {1}", item.ToString(), item.ToFormattedString());

Output:

120.5 => 120.50
110 => 110
25.356 => 25.356

You can write a method to get you the number of decimal places in the number like this:

private static int GetDecimalPlaces(decimal number)
{
    return number.ToString().IndexOf('.') == -1 ? 0 :
        number.ToString().Substring(number.ToString().IndexOf('.') + 1).Length;   
}

Then you can use Fx specifier where x is the number of decimal places like this:

value1.ToString("F" + GetDecimalPlaces(value1))

Try Me .


Localization

If you care about localization, then use the code below so it will work for any culture since some cultures use , as decimal:

private static int GetDecimalPlaces(decimal number)
{
    char decimalSeparator = 
        Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);
    var index = number.ToString().IndexOf(decimalSeparator);
    return index == -1 ? 0 : number.ToString().Substring(index + 1).Length;
}

There are various formats as shown on MSDN . Here is some code copy pasted from there:

decimal value = 16325.62m;
string specifier;

// Use standard numeric format specifiers.
specifier = "G";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    G: 16325.62
specifier = "C";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    C: $16,325.62
specifier = "E04";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    E04: 1.6326E+004
specifier = "F";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    F: 16325.62
specifier = "N";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    N: 16,325.62
specifier = "P";
Console.WriteLine("{0}: {1}", specifier, (value/10000).ToString(specifier));
// Displays:    P: 163.26 %

// Use custom numeric format specifiers.
specifier = "0,0.000";
Console.WriteLine("{0}: {1}", specifier, value.ToString(specifier));
// Displays:    0,0.000: 16,325.620
specifier = "#,#.00#;(#,#.00#)";
Console.WriteLine("{0}: {1}", specifier, (value*-1).ToString(specifier));
// Displays:    #,#.00#;(#,#.00#): (16,325.62)

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