Skip to content

WebApi result lost decimal property's precision? #58868

Answered by engineering87
Rorschach331 asked this question in Q&A
Discussion options

You must be logged in to vote

Hello @Rorschach331,
to preserve the full precision, you can work around return it as a string.
If you need it to remain a number, you'll have to write a custom JsonConverter for decimal to control the formatting:

public class DecimalJsonConverter : JsonConverter<decimal>
{
    public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        => reader.GetDecimal();

    public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
    {
        writer.WriteRawValue(value.ToString("G29", System.Globalization.CultureInfo.InvariantCulture));
    }
}

In your Program.cs:

builder.Services.Configure<Microsoft.Asp…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Rorschach331
Comment options

Answer selected by Rorschach331
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants