Automapper Round All Decimal Type Instances

3.1k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

The answer provided above is correct. Just wanted to point out that we can also achieve this using AutoMapper's MapperConfiguration as well, instead of Profiles.

We can modify the above code to use MapperConfiguration as follows.

Define the Foo class

public class Foo
{
        public decimal X { get; set; }
}

Modify the main method as follows:

class Program
{
    private IMapper _mapper;

    static void Main(string[] args)
    {
        InitialiseMapper();

        var foo = new Foo() { X = 1234.4567M };
        var foo2 = _mapper.Map<Foo>(foo);
        Debug.WriteLine(foo2.X);
    }

    private void InitialiseMapper()
    {
        var mapperConfig = new MapperConfiguration(cfg =>
            {
                CreateMap<decimal, decimal>().ConvertUsing(x=> Math.Round(x,2));
                CreateMap<Foo, Foo>();                   
            });

            _mapper = mapperConfig.CreateMapper();            
    }
}