1

Closed

Strange decimal xml serialization

description

When using JsonConvert.DeserializeXNode some decimals (bigger than some value) serialize/deserialize with error.

For example 1000000003.14159265358979 serializes to 1000000003.1415926.
but 3.14159265358979 serializes to 3.14159265358979

Test:

    public class TestDecimal
    {
        public class Container { public decimal Number { get; set; } }

        private static IEnumerable<TestCaseData> Values
        {
            get
            {
                yield return new TestCaseData((decimal)Math.PI);
                yield return new TestCaseData((decimal)Math.PI + 1000000000m);
            }
        }
            
        [Test]
        [TestCaseSource("Values")]
        public void TestMe(decimal value)
        {
            var x = new Container() { Number = value };

            var json = JsonConvert.SerializeObject(x);
            var xml = JsonConvert.DeserializeXNode(json);
            var val = xml.ToString();
            Assert.That(val, Is.StringContaining(value.ToString(CultureInfo.InvariantCulture)));
        }
    }
Closed Apr 25 at 11:34 AM by JamesNK

comments

JamesNK wrote Apr 25 at 11:33 AM

I have made some changes so that next version you can do this and keep the decimal precision:
XDocument doc1 = JsonConvert.DeserializeObject<XDocument>(json, new JsonSerializerSettings
{
    Converters = { new XmlNodeConverter() },
    FloatParseHandling = FloatParseHandling.Decimal
});