You're explicitly formatting the values. Don't do that - add the elements directly to the array:
if (value is List<double> myList)
{
JArray myArray = new JArray();
foreach (var element in myList)
{
myArray.Add(element);
}
myArray.WriteTo(writer);
}
Or write directly to the writer:
if (value is List<double> myList)
{
writer.WriteStartArray();
foreach (var element in myList)
{
writer.WriteValue(element);
}
writer.WriteEndArray();
}
This may not get to the exact representation you want (in terms of scientific notation), but it will get to a valid JSON representation of the data you're trying to serialize. Anything reading the JSON should be able to read the exact same value from the JSON.
If you absolutely have to customize the format, you can use JsonWriter.WriteRawValue
, using the invariant culture to format your values. But I'd strongly advise you not to. I'd be really surprised at a JSON parser that can't handle the regular output of Json.NET. Here's a complete example if you really, really have to do it:
using System;
using System.Globalization;
using System.Collections.Generic;
using Newtonsoft.Json;
class Program
{
static void Main(string[] args)
{
var writer = new JsonTextWriter(Console.Out);
var list = new List<double>
{
-9.811880E-002,
2.236657E-002,
-4.020144E-001
};
WriteList(writer, list);
}
static void WriteList(JsonWriter writer, List<double> list)
{
writer.WriteStartArray();
foreach (var element in list)
{
writer.WriteRawValue(element.ToString("E", CultureInfo.InvariantCulture));
}
writer.WriteEndArray();
}
}
Output:
[-9.811880E-002,2.236657E-002,-4.020144E-001]