Number decimal precision with System.Text.Json

411 views Asked by At

How do I write (serialize) a float to JSON with fixed 2 decimals using System.Text.Json?

Like {"Amount": 12.30}.

Not like {"Amount": 12.3} or {"Amount": 12.3001} or {"Amount": "12.30"}.

It seems there is no decimal precision option for float (or decimal or double or whatever), in JsonWriterOptions or either in JsonSerializerOptions. Also writing own converter seems to be unclear: Utf8JsonWriter writer WriteWhat?

2

There are 2 answers

1
Tuomas Hietanen On

Ok found it, raw converter seems to work:

type TwoDecimalsConverter() =
    inherit System.Text.Json.Serialization.JsonConverter<float>()

    override _.Write(writer: System.Text.Json.Utf8JsonWriter, value, serializer) =
        writer.WriteRawValue(value.ToString "0.00")

    override _.Read(reader, typeToConvert, options) =
        failwith "Not implemented"
0
alphons On
public class JsonConverterDouble : JsonConverter<double>
{
    public override double Read(ref Utf8JsonReader reader,
        Type typeToConvert, JsonSerializerOptions options)
    {
        return reader.GetDouble();
    }

    public override void Write(Utf8JsonWriter writer, double value,
        JsonSerializerOptions options)
    {
        writer.WriteRawValue(value.ToString("0.##",
            CultureInfo.InvariantCulture));
    }
}

Converters can be used in JsonSerializerOptions, for example:

var json = JsonSerializer.Serialize(data, new JsonSerializerOptions()
{
    Converters = { new JsonConverterDouble() }
});

You can change the formatting "0.##" for your needs.

This sollution works, but is a little slow when using CreateSpecificCulture use CultureInfo.InvariantCulture for speed.