applejag/Newtonsoft.Json-for-Unity.Converters

Bug: Float values lose precision when deserialized.

CortiWins opened this issue · 1 comments

In PartialFloatConverter the Method ReadValue uses JsonReader.ReadAsDouble which in my case reads the float text representations with a noticable loss in precision.

Example: 0.000000156f is saved as "1.56E-07" and parsed by JsonReader.ReadAsDouble as "1.23E-09".

My fix:

protected override float ReadValue(JsonReader reader, int index, JsonSerializer serializer)
{
    // Changed to ReadAsString and parse, as the previous "JsonReader.ReadAsDouble" lost precision.
    var valueText = reader.ReadAsString();
    
    if (float.TryParse(
        valueText,
        System.Globalization.NumberStyles.Any,
        System.Globalization.CultureInfo.InvariantCulture, out var valueParsed))
    {
        return valueParsed;
    }
    else
    {
        return 0f;
    }
}

protected override void WriteValue(JsonWriter writer, float value, JsonSerializer serializer)
{
    writer.WriteValue(value.ToString(System.Globalization.CultureInfo.InvariantCulture));
}

Nice work btw.

Hey this is a very nice find! Super with the sample solution as well!

Sorry for delay, but I'm starting to implementing the fix right about now :)