I’m encountering an issue with System.Text.Json in C# related to the serialization of floating-point numbers. When serializing a float with a decimal part (e.g., 4.0), the library seems to omit the decimal part, resulting in the JSON representation being just 4 instead of 4.0.
I’ve tried using various configurations, including setting NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals and NumberHandling = JsonNumberHandling.WriteAsString, but the behavior remains the same.
Is there a way to preserve the complete representation (e.g., 4.0) during serialization, or is there a known limitation with the current version of System.Text.Json?
Thank you for any insights or suggestions.
2
Answers
Thank you for your comments,
Here's how I fixed the problem:
Creating a Class :
Add serializer option :
JSON does not distinguish between
float
andint
, it only has a concept of Number so in general you should avoid relying on the particular number formatting.If currently you can’t fix the app which uses the JSON you can use custom converter which will use specific number format. For example:
And usage: