Search code examples
c#.netf#system.text.jsonjson-serialization

Number decimal precision with System.Text.Json


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?


Solution

  • 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"