Skip to content

Commit

Permalink
Use 17 digits of precision with Double.ToString
Browse files Browse the repository at this point in the history
Using 15 digits ("R") leads to failure of roundtrip
serialization/deserialization.

See also https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring

Another example is 0.6822871999174
  • Loading branch information
oleks committed Feb 22, 2023
1 parent 5702581 commit f067837
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
10 changes: 9 additions & 1 deletion Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1589,6 +1589,14 @@ public void CustomDoubleRounding()
Assert.AreEqual("{\"Positions\":[57.72,60.44,63.44,66.81,70.45],\"Loads\":[23284.0,23225.0,23062.0,22846.0,22594.0],\"Gain\":12345.679}", json);
}

[Test]
public void DoubleRoundTrip()
{
var x = 0.1 + 0.2;
var y = JsonConvert.DeserializeObject<double>(JsonConvert.SerializeObject(x));
Assert.AreEqual(x, y);
}

public class Measurements
{
[JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))]
Expand Down Expand Up @@ -1830,4 +1838,4 @@ private int _expiration
public DateTime Expiration { get; set; }
}
}
}
}
2 changes: 1 addition & 1 deletion Src/Newtonsoft.Json/JsonConvert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,7 @@ private static string EnsureFloatFormat(double value, string text, FloatFormatHa
/// <returns>A JSON string representation of the <see cref="Double"/>.</returns>
public static string ToString(double value)
{
return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
return EnsureDecimalPlace(value, value.ToString("G17", CultureInfo.InvariantCulture));
}

internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
Expand Down

0 comments on commit f067837

Please sign in to comment.