gpt4 book ai didi

c# - Automapper 将 Decimals 设置为 2 位小数

转载 作者:行者123 更新时间:2023-12-02 13:25:38 27 4
gpt4 key购买 nike

我想使用 AutoMapper 链接我的两个对象。它运行良好,但现在我想将我的小数项格式化为四舍五入到小数点后两位。

这就是我所拥有的。我做错了什么?

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

这是 RoundDecimalTwo 格式化程序

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

最佳答案

您可能不知道的一件事是,默认情况下,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();

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

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

关于c# - Automapper 将 Decimals 设置为 2 位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5111432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com