Reputation: 127
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.
In the console network tab-
Upvotes: 2
Views: 1947
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:
Upvotes: 2