I need a way to add rounding to my automapper configuration. I have tried using the IValueFormatter as suggested here: Automapper Set Decimals to all be 2 decimals
But AutoMapper no longer supports formatters. I don't need to covert it to a different type, so I'm not sure a type converter is the best solution either.
Is there still a good automapper solution for this problem now?
Using AutoMapper version 6.11
This is a complete MCVE demonstrating how you can configure the mapping of decimal
to decimal
. In this example I round all decimal values to two digits:
public class FooProfile : Profile
{
public FooProfile()
{
CreateMap<decimal, decimal>().ConvertUsing(x=> Math.Round(x,2));
CreateMap<Foo, Foo>();
}
}
public class Foo
{
public decimal X { get; set; }
}
Here, we demonstrate it:
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(x=> x.AddProfile(new FooProfile()));
var foo = new Foo() { X = 1234.4567M };
var foo2 = Mapper.Map<Foo>(foo);
Debug.WriteLine(foo2.X);
}
}
Expected output:
1234.46
While its true that Automapper knows how to map a decimal
to a decimal
out of the box, we can override its default configuration and tell it how to map them to suit our needs.