How can I force a minimum number of decimal places in Json.net?

You can do it with a custom JSON converter:

class DecimalJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return 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.WriteRawValue(((decimal) value).ToString("F2", CultureInfo.InvariantCulture));
    }
}

This is a very basic converter. You may need to extend it to support other floating-point types, or perhaps even integer types too.

Now instantiate your serialiser and pass it your custom converter, like so:

var serializer = new JsonSerializer();
serializer.Converters.Add(new DecimalJsonConverter());

Leave a Comment