简体   繁体   English

将小数格式化为货币

[英]Format a Decimal to Currency

I have a list of decimals that I want to be able to format as US currency. 我有一个小数清单,希望将其格式化为美国货币。 I know I can do this with string.format but if I convert the decimals to a string they no long sort properly 我知道我可以使用string.format来做到这一点,但是如果我将小数转换为字符串,它们将无法正确排序

1234.98
91234.12
541234.12

When converted to currency using string.format they will sort in this order 当使用string.format转换为货币时,它们将按此顺序排序

$91,234.12
$541,234.12
$1,234.98

I want them to stay as decimals so they sort correctly as 我希望它们保留为小数,以便它们正确排序为

$541,234.12
$91,234.12
$1,234.98

Keep them as decimals within the list or container you are using to sort, and simply use string format on them when displaying. 将它们保留为小数点放在要排序的列表或容器中,并在显示时简单地使用字符串格式。 I don't understand the need have them as both a string and a decimal at the same time when you can display it anyway you wish. 我不明白当您希望以任何方式显示时,需要同时将它们同时作为字符串和十进制。

I see two main options for you here. 在这里,我为您提供了两个主要选择。 The first is to zero-pad your numbers ( $001,234.98 ) which seems like it would directly oppose most user's preferred experiences. 第一种是将您的数字零填充( $001,234.98 ),这似乎直接反对大多数用户的首选体验。

Another option could be to create a type for currency: 另一种选择是为货币创建类型:

public class Currency : IComparable
{
    public decimal Value { get; set; }

    public int CompareTo(Currency b)
    {
        return Value.CompareTo(b.Value);
    }

    public override string ToString()
    {
        return Value.ToString("C");
    }
}

You'd want to override Equals and GetHashCode , of course. 您当然想覆盖EqualsGetHashCode This would display sorted as expected (control properties permitting), but it would also display as expected. 这将按预期显示排序(控制属性允许),但也将按预期显示。 You might want to make the class into an immutable struct , of course, too. 当然,您可能也想将类设为不可变的struct But this is just meant to show the gist. 但这只是为了显示要点。

A class like this would also provide very good LINQ support, in that you could have an IEnumerable<T> and simply call OrderBy(c => c) . 这样的类也将提供很好的LINQ支持,因为您可以拥有IEnumerable<T>并只需调用OrderBy(c => c) You could even print out the values on lines by calling string.Join(Environment.NewLine, coll.OrderBy(c => c)) , which is very clean. 您甚至可以通过调用string.Join(Environment.NewLine, coll.OrderBy(c => c))来打印string.Join(Environment.NewLine, coll.OrderBy(c => c))的值,这非常干净。

Of course, a class like this should only be used for UI code. 当然,这样的类只能用于UI代码。 You wouldn't want to deal with serializing it or anything like that, since it'd provide unnecessary overhead. 您不需要处理序列化之类的东西,因为它会提供不必要的开销。

Create a class that holds the decimal and its appropriate formatted string. 创建一个包含小数及其适当格式的字符串的类。 Use Linq to sort the class objects by the decimal. 使用Linq按十进制对类对象进行排序。

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

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