Question

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.

Was it helpful?

Solution

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

OTHER TIPS

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

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.

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

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top