简体   繁体   English

C#中十进制到字符串的转换

[英]decimal to string conversion in C#

How can I convert a list of decimal values to strings such that:如何将decimal值列表转换为字符串,以便:

  • 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.ToString 覆盖来指定格式。

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

This can also be used when using String.Format.这也可以在使用 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. OP 和注释中提供了对代码的注释。

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:然后您可以使用Fx说明符,其中 x 是小数位数,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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