Automapper将小数设置为2位小数

col*_*nde 2 c# mapping automapper

我想使用AutoMapper链接我的两个对象.它运行良好,但现在我想将我的小数项格式化为全数字2到2位小数.

这就是我所拥有的.我究竟做错了什么?

Mapper.CreateMap<Object1, Object2>()
.ForMember(x => typeof(decimal), x => x.AddFormatter<RoundDecimalTwo>());
Run Code Online (Sandbox Code Playgroud)

这是RoundDecimalTwo格式化程序

public class RoundDecimalTwo : IValueFormatter
    {
        public string FormatValue(ResolutionContext context)
        {
            return Math.Round((decimal)context.SourceValue,2).ToString();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Kei*_*thS 6

您可能不知道的一件事是默认情况下,Math.Round舍入到最低有效数字的最接近的偶数("银行家舍入"),而不是简单地达到LSD的下一个整数值("对称算术舍入" ",你在小学阶段学到的方法.因此,7.005的值将舍入到7(7.00),而不像Krabappel夫人教你的那样7.01.原因在于MSDN的math.round页面:http://msdn.microsoft.com/en-us/library/system.math.round.aspx

要更改此设置,请确保将第三个参数添加MidpointRounding.AwayFromZero到您的回合中.这将使用您熟悉的舍入方法:

return Math.Round((decimal)context.SourceValue,2, MidpointRounding.AwayFromZero).ToString();
Run Code Online (Sandbox Code Playgroud)

此外,要确保即使一个或两个都为零,也始终显示两个小数位,请在ToString函数中指定数字格式."F"或"f"是好的; 他们将以"定点"格式返回数字,在美国文化中默认为2(您可以通过指定小数位来覆盖默认值):

return Math.Round((decimal)context.SourceValue,2, MidpointRounding.AwayFromZero).ToString("F2");
Run Code Online (Sandbox Code Playgroud)

  • 如果我能为Curbopple夫人准备,我会给予额外的+1. (4认同)