简体   繁体   中英

C# JSONConvert Changing float value?

Im consuming a Web API using JSON , where one of the properties of the object I am bringing back is of type FLOAT.

After inserting the data into the database I started noticing some strange results here and there. I have just stepped through the code and I can see that the value of the float property "PERSUNQ":124736684.0 .

However, the minute that I touch the JSON data using JSONConvert, the value magically changes to :124736688.0

 GRSAPIData = client.DownloadString(GRSURL);   <!--- value is correct

 Rootobject root = (Rootobject)JsonConvert.DeserializeObject<Rootobject>(GRSAPIData); <-- value is magically changed

The two lines above are one after the other (no code in between) and I assue you ive checked everywhere and I am not changing the value myself.

Is there something I should be aware of when using JSONConvert when dealing with floats that can explain this behaviour?

Thanks in advance

A float only has 7 digits of precision - that leading to the problem you're seeing. You can see this without getting JSON involved at all:

using System;

class Program
{
    static void Main(string[] args)
    {
        float f = 124736684.0f;
        Console.WriteLine(f.ToString("r")); // Round-trip
    }
}

Output:

124736688

Basically, the closest representable float value to 124736684 is 124736688.

It looks like you should probably use double instead - or potentially decimal , depending on what the value is meant to represent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM