You can use custom converter which rounds each decimal value to given number of fraction digits:
public class JsonDecimalConverter : JsonConverter
{
private int decimals;
public JsonDecimalConverter(int decimals = 2)
{
this.decimals = decimals;
}
public override bool CanConvert(Type objectType) => objectType == typeof(decimal);
public override object ReadJson(JsonReader reader,
Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer,
object value, JsonSerializer serializer)
{
writer.WriteValue(Decimal.Round((decimal)value, decimals));
}
}
Usage:
var thing = new Thing { Amount = 40.12345M, Name = "Foo" };
var json = JsonConvert.SerializeObject(thing, new JsonDecimalConverter());
Output:
{
"Amount": 40.12,
"Name": "Foo"
}
Note that this will give you 40
for decimal number 40
. Because there are no meaningful digits to be stored. 40.00
is a string formatting issue which you should handle where you want to display or store this decimal representation.