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

Does anyone know how I can get a format string to use bankers rounding ? I used "{0: c}", but that’s not how bankers rounding does. The Math.Round() method does rounding of bankers. I just need to be able to duplicate the rounding method using a format string.


Note: the original question was pretty tricky, and from that come the answers that mention the regex.

+4
source share
5 answers

Can't you just call Math.Round () to enter a string to get the behavior you want?

Instead:

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

make:

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

Regexp is a pattern matching language. You cannot perform arithmetic operations in Regexp.

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

+3
source

Impossible, the regular expression does not have the concept of "number". You can use the match evaluator , but you would add the imperative C # code and deviate from your requirement for the regular expression only.

0
source

.Net has built support for both rounding arithmetic and bankers:

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

Even "rounding" is actually a default, although "from scratch" is what you learned at school.

This is due to the fact that under the hood, computer processors also round off bankers.

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

I would think that any line in the rounding format will round off bankers by default, right?

0
source

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(); 
0
source

Source: https://habr.com/ru/post/1277118/


All Articles