WebApi result lost decimal property's precision? #58868
Answered
by
engineering87
Rorschach331
asked this question in
Q&A
-
use the simple web api template:
when i call the api in the swagger,i get a json like this:
the amount value is |
Beta Was this translation helpful? Give feedback.
Answered by
engineering87
Aug 7, 2025
Replies: 1 comment 1 reply
-
Hello @Rorschach331, 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.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new DecimalJsonConverter());
}); and use: record WeatherForecast(decimal Amount);
app.MapGet("/weatherforecast", () =>
{
var forecast = new WeatherForecast(19493.7797202797203M);
return forecast;
}); Try and let me know. |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
Rorschach331
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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:
In your Program.cs: