user21767
user21767

Reputation: 95

.NET currency formatter: can I specify the use of banker's rounding?

Does anyone know how I can get a format string to use bankers rounding? I have been using "{0:c}" but that doesn't round the same way that bankers rounding does. The Math.Round() method does bankers rounding. I just need to be able to duplicate how it rounds using a format string.


Note: the original question was rather misleading, and answers mentioning regex derive from that.

Upvotes: 5

Views: 2538

Answers (5)

Abe Heidebrecht
Abe Heidebrecht

Reputation: 30498

If you are using .NET 3.5, you can define an extension method to help you do this:

public static class DoubleExtensions
{
    public static string Format(this double d)
    {
        return String.Format("{0:c}", Math.Round(d));
    }
}

Then, when you call it, you can do:

12345.6789.Format();

Upvotes: 0

Keith
Keith

Reputation: 155662

.Net has built in support for both Arithmetic and Bankers' rounding:

//midpoint always goes 'up': 2.5 -> 3
Math.Round( input, MidpointRounding.AwayFromZero );

//midpoint always goes to nearest even: 2.5 -> 2, 5.5 -> 6
//aka bankers' rounding
Math.Round( input, MidpointRounding.ToEven );

"To even" rounding is actually the default, even though "away from zero" is what you learnt at school.

This is because under the hood computer processors also do bankers' rounding.

//defaults to banker's
Math.Round( input );

I would have thought that any rounding format string would default to bankers' rounding, is this not the case?

Upvotes: 0

jop
jop

Reputation: 84043

Regexp is a pattern matching language. You can't do arithmetic operations in Regexp.

Do some experiements with IFormatProvider and ICustomFormatter. Here is a link might point you in the right direction. http://codebetter.com/blogs/david.hayden/archive/2006/03/12/140732.aspx

Upvotes: 2

Zach Lute
Zach Lute

Reputation: 611

Can't you simply call Math.Round() on the string input to get the behavior you want?

Instead of:

string s = string.Format("{0:c}", 12345.6789);

Do:

string s = string.Format("{0:c}", Math.Round(12345.6789));

Upvotes: 4

viggity
viggity

Reputation: 15237

Its not possible, a regular expression doesn't have any concept of "numbers". You could use a match evaluator but you'd be adding imperative c# code, and would stray from your regex only requirement.

Upvotes: 0

Related Questions