0

In my ASP.NET Core application I am using the built-in System.Text.Json serializer to convert EF models to DTOs. On one of my models, I have a property that represents a percentage and I map that to a DTO property. Before returning the value to the client, I convert the value to a percentage. However, I am finding out that if my DTO property is a double and I serialize it I get odd results when doing the percentage conversion. It seems to work as expected when using a decimal property in my DTO. Anyone have an idea of how to fix this?

Here is an illustration of the problem....

    var test = .14M;
    var formatted = test * 100;
    var bytes = System.Text.Json.JsonSerializer.Serialize(formatted);

Serialized Result = 14.00

    var test = .14d;
    var formatted = test * 100;
    var bytes = System.Text.Json.JsonSerializer.Serialize(formatted);

Serialized Result = 14.000000000000002

  • Binary floating-point is not exact with regards to decimal digits. The serializer does try to serialize the exact value, just in case you need to round-trip. Check `formatted.ToString("G17")` to see what I mean. The same does not apply to `decimal`, which (as the name implies) is a decimal floating-point type that can store your value exactly. – Jeroen Mostert Dec 15 '21 at 15:47
  • I changed the code that does the conversion to force the math to use decimals and then convert it back to a double. var formatted = Convert.ToDouble(Convert.ToDecimal(value) * 100M) seems to be an okay workaround for now. – Michael Ceranski Dec 15 '21 at 16:35

0 Answers0