asp.net-coreserializationjson.netscientific-notation

How to serialize double to JSON without scentific notation Newtonsoft JSON.NET?


ASP.NET Core app uses Newtonsoft JSON.NET for serialization:

builder.Services.AddControllers().AddNewtonsoftJson();

There is some model with property of type double:

public class SomeModel
{
    public double Number { get; set; } = 0.0000000100000000000000001234567;
}

And also this controller:

[ApiController]
public class HomeController : ControllerBase
{
    [HttpGet]
    [Route("/")]
    public SomeModel Index()
    {
        return new SomeModel();
    }
}

The result is json {"number":1E-08}.

The expected result is {"number": 0.0000000100000000000000001234567}. How can this be achieved?

I've already tried using FloatParseHandling = FloatParseHandling.Decimal and creating new converter, but scientific notation remains.


Solution

  • you have to specify format from beginning this example should help you to understand and how to convert its also rounding:

    void Main()
    {
        var x = new SomeModel().Number;
        Console.WriteLine(x);
        Console.WriteLine(decimal.Parse(x.ToString(), NumberStyles.Float));
    
        var x2 = new SomeModel().Number2;
        Console.WriteLine(x2);
        Console.WriteLine(decimal.Parse(x2.ToString(), NumberStyles.Float));
        Console.WriteLine(decimal.Parse(new SomeModel().Number3.ToString(), NumberStyles.Float));
    }
    
    public class SomeModel
    {
        public double Number { get; set; } = 0.0000000100000000000000001234567;
        public double Number2 { get; set; } = 0.0000000100000000000000001234567F;
        public decimal Number3 { get; set; } = 0.0000000100000000000000001234567M;
    }
    

    result would be

    1E-08
    0.00000001
    9.99999993922529E-09
    0.00000000999999993922529
    0.0000000100000000000000001235
    

    serialized {"Number":1E-08,"Number2":9.99999993922529E-09,"Number3":0.0000000100000000000000001235}