Reputation:
I use System.Text.Json to deserialize some stuff and then serialize it. The problem is that for example double value 99.6 is being deserialized and then serialized to 99.599999999999994.
What can I do about it?
Here's a reproduction in console app.
using System;
using System.Text.Json;
namespace ConsolePG3
{
class Program
{
static void Main(string[] args)
{
Person person = new Person { Value = 99.6 };
var text = JsonSerializer.Serialize(person);
Console.WriteLine(text);
Console.ReadLine();
}
}
class Person
{
public double Value { get; set; }
}
}
Upvotes: 3
Views: 3170
Reputation: 1062650
The important thing to get your head around here is that the double
with value 99.6
does not exist, and never existed. You imagined it. It was rounded the moment you compiled it. It is simply not possible to represent the exact value 99.6
in floating-point arithmetic, due to how floating-point works. The serializer has correctly serialized the actual value that exists.
If you want to represent discreet values in the way that humans tend to think of them - use decimal
instead of floating-point (float
, double
). It (decimal
) is also limited in terms of precision (and it is not CPU-optimized), but the way it approximates is much more comparable to how humans approximate, and it will readily story the exact value for most common scenarios.
Frankly, the moment you are thinking about "the exact value": floating point is not a good choice.
Upvotes: 10