Ironsides24
Ironsides24

Reputation: 37

Format a Decimal to Currency

I have a list of decimals that I want to be able to format as U.S. 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

Upvotes: 1

Views: 477

Answers (3)

Matthew Haugen
Matthew Haugen

Reputation: 13286

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.

Upvotes: 2

Create a class that holds the decimal and its appropriate formatted string. Use Linq to sort the class objects by the decimal.

Upvotes: -1

ForeverZer0
ForeverZer0

Reputation: 2496

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.

Upvotes: 4

Related Questions