C.Das
C.Das

Reputation: 127

Adding two decimal point .00 when returning the result from web API

I have a asp.net core web API project in that when I am returning a JSON result to the UI all the decimal values is converting to whole number, when I debug the controller I can see that two decimal point .00 but when I check it in the console network tab it is coming as whole number.

So, how can I add a formatter that will keep the decimal value as it is that is coming from the DB, it should not convert it to a whole number by the time it reaches the UI.

When I debug the controller - enter image description here

In the console network tab-

enter image description here

Upvotes: 2

Views: 1947

Answers (1)

mj1313
mj1313

Reputation: 8459

You could custom serializer for the decimal property

public class TestModel
{
    [JsonConverter(typeof(DecimalConverter))]
    public decimal Price { get; set; }
}

public class DecimalConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(decimal));
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(((decimal)value).ToString("0.00"));
    }

    public override bool CanRead
    {
        get { return false; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Result:

enter image description here

Upvotes: 2

Related Questions