2

I want to use AutoMapper to link up two of my objects. It is working well but now I want to format my decimal items to all round to 2 decimals.

This is what I have. What am I doing wrong?

Mapper.CreateMap<Object1, Object2>()
.ForMember(x => typeof(decimal), x => x.AddFormatter<RoundDecimalTwo>());

Here is the RoundDecimalTwo Formatter

public class RoundDecimalTwo : IValueFormatter
    {
        public string FormatValue(ResolutionContext context)
        {
            return Math.Round((decimal)context.SourceValue,2).ToString();
        }
    }
colemande
  • 392
  • 1
  • 5
  • 17

2 Answers2

7

One thing you may not know is that Math.Round, by default, rounds to the nearest EVEN number for the least significant digit ("bankers' rounding"), not simply up to the next integer value of the LSD ("symmetric arithmetic rounding", the method you learned in grade school). So, a value of 7.005 will round to 7 (7.00), NOT 7.01 like Mrs. Krabappel taught you. The reasons why are on the math.round page of MSDN: http://msdn.microsoft.com/en-us/library/system.math.round.aspx

To change this, make sure you add a third parameter, MidpointRounding.AwayFromZero, to your round. This will use the rounding method you're familiar with:

return Math.Round((decimal)context.SourceValue,2, MidpointRounding.AwayFromZero).ToString();

Additionally, to make sure two decimal places are always shown even when one or both are zero, specify a number format in the ToString function. "F" or "f" are good; they'll return the number in a "fixed-point" format which in US cultures defaults to 2 (you can override the default by specifying the number of decimals):

return Math.Round((decimal)context.SourceValue,2, MidpointRounding.AwayFromZero).ToString("F2");
Jamie Ide
  • 45,803
  • 16
  • 74
  • 115
KeithS
  • 65,745
  • 16
  • 102
  • 161
0

Use Math.Round like below:

Math.Round(yourDoubleValue, 2,MidpointRounding.AwayFromZero);
Abdus Salam Azad
  • 3,109
  • 31
  • 23