From f0678379557ace247a6697af296e9849d8e8590e Mon Sep 17 00:00:00 2001 From: Oleks Date: Wed, 22 Feb 2023 18:32:14 +0100 Subject: [PATCH 1/2] Use 17 digits of precision with Double.ToString 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 --- Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | 10 +++++++++- Src/Newtonsoft.Json/JsonConvert.cs | 2 +- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs index 2582f43a3..0a9925b71 100644 --- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs @@ -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(JsonConvert.SerializeObject(x)); + Assert.AreEqual(x, y); + } + public class Measurements { [JsonProperty(ItemConverterType = typeof(RoundingJsonConverter))] @@ -1830,4 +1838,4 @@ private int _expiration public DateTime Expiration { get; set; } } } -} \ No newline at end of file +} diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index 95019e2b7..a047d679a 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -292,7 +292,7 @@ private static string EnsureFloatFormat(double value, string text, FloatFormatHa /// A JSON string representation of the . 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) From 0796691e92cb60e8d9a1459f5d0176bd216fa1f7 Mon Sep 17 00:00:00 2001 From: Oleks Date: Wed, 22 Feb 2023 18:37:39 +0100 Subject: [PATCH 2/2] Make sure to use same type for AreEqual arguments --- Src/Newtonsoft.Json.Tests/JsonConvertTest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs index 0a9925b71..f5ac38ef9 100644 --- a/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonConvertTest.cs @@ -1592,8 +1592,8 @@ public void CustomDoubleRounding() [Test] public void DoubleRoundTrip() { - var x = 0.1 + 0.2; - var y = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x)); + double x = 0.1 + 0.2; + double y = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(x)); Assert.AreEqual(x, y); }