简体   繁体   中英

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

1234.98
91234.12
541234.12

When converted to currency using string.format they will sort in this order

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

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. 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. 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) . You could even print out the values on lines by calling string.Join(Environment.NewLine, coll.OrderBy(c => c)) , which is very clean.

Of course, a class like this should only be used for UI code. 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.

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