Search code examples
.netserializationdoubleprecisionsystem.text.json

Serialising .NET object to JSON: `double` property value gets written as a different value with extra decimal places


I'm using System.Text.Json to (de)serialise between .NET Well class object and JSON. The Well class object has a List of layers List<Layer> layers, and the Layer class has a list of Items List<Item> items The Item class has properties such as string name, double length. The classes are as below:

public class Well
{
    public string name {get; set;}
    public List<Layer> layers {get; set;}
    
    public void serialiseJSON()
    {
        string fileName = "well.json";
        string jsonString = JsonSerialiser.Serialize(this);
        File.WriteAllText(fileName, jsonString);
        return;
    }
}
public class Layer
{
    public string name {get; set;};
    public List<Item> items {get; set;}
}
public class Item
{
    public string name {get; set;};
    public double length {get; set;}
}

for example when the item.length value is 70.8, it gets written to file as 70.799999999999997 after serialising the Well. As far as I can understand, and please correct me if I'm wrong, this is due to the the precision of the double data type but I don't udnerstand why the double value gets written differently. The class instance has the correct value but serialising it to a json file changes it in the file. Any help would be greatly appreciated.

Note: I do not wish to save the double values as string in my json file for consistency reasons.


Solution

  • I managed to fix this issue by changing the Item members to decimal type

    public class Item
    {
        public string name {get; set;};
        public decimal length {get; set;}
    }