Automapper Set Decimals to all be 2 decimals

大憨熊 提交于 2019-12-07 22:34:52

问题


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

回答1:


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



回答2:


Use Math.Round like below:

Math.Round(yourDoubleValue, 2,MidpointRounding.AwayFromZero);


来源:https://stackoverflow.com/questions/5111432/automapper-set-decimals-to-all-be-2-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!