-1

JsonSerializer saves float values in JSON file in exponential notation ( like 1.774073E-05 ) How to change its settings so values are saved as regular floats, i.e. 0.0001774073 ?

string text = File.ReadAllText(path, Encoding.UTF8);
JObject json = JObject.Parse(text);

using (StreamWriter file = File.CreateText(savePath))
{
    JsonSerializer serializer = new JsonSerializer();
    serializer.Serialize(file, json);
}
yaru
  • 1,260
  • 1
  • 13
  • 29
  • Floats are exponential/scientific notation. If you need precision, you hae to use a integer. Maybe a fixed with decimal (Currency?) https://www.youtube.com/watch?v=PZRI1IfStY0 – Christopher Sep 22 '19 at 10:24
  • I am reading floats from another JSON. And there they are stored as regular numbers like `0.33714828` I think there is a way to store them without `E-05` suffix – yaru Sep 22 '19 at 11:14
  • How is the float expressed in your JSON file stored? Running your code gives back float number in same format (0.0001774073) and not in exponential notation (1.774073E-05). – tyrion Sep 22 '19 at 14:54
  • https://stackoverflow.com/a/32726630/1056253 I wrote custom JsonConverter class and it worked. – yaru Sep 22 '19 at 18:33

1 Answers1

0

I need to make sure you undertand this part: Floats are scientific/exponential notation. The memory reserved for a float contains the mantisse (signiticant digits) and the exponent over 10. That exponent is how the floating (moveable) part of floating point works. That is how they cover value from "size of the universe" to "size of the atom" ranges.

You can represent them as a human reable number. But doing so needs so insanely many zeroes, most people do not bother. 45-38 zeroes for float in fact. And it will not get you any additonal data or precision, as the math is still done by the CPU in float notation. Writing them out with Zeroes is just a pointless waste of characters (and thus bytes), so outside of input from or output towards the user, nobody will bother.

Not that I think 150,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000 is really that human readable to begin with. Honestly 1.5 * 10^45 seems way more readable for me. And everyone that else would ever use such a number.

Christopher
  • 9,634
  • 2
  • 17
  • 31