Interesting Relation Between C# And JavaScript For 64-bit number

Let's assume that you are working on one application. Scenario is that, we may have large number of rows present in database and for primary key we can either use int Id or bigint Id. int is 32-bit and bigint is 64-bit.

In C#, long is 64-bit datatype, so if you have store value in DB that is as bigint and its max value is 9223372036854775807.

if you read from DB and return that as a result for example web api response. It looks like following.

[HttpGet]
public IActionResult Get()
{
     var obj = new { Id = long.MaxValue, Name = "test" };
     return Ok(obj);
}

Result is look like following.

image.png

So far so good.

Now if same json result that we get in response of postman. It works same in browser. Yes.. It must work.. but really ?

I am using browse console window.

image.png

See, it seems that it get truncated. This is due to fact that JavaScript support 53 bit number with remaining bit to for precision. More detail you will find here. More info

Now what is the solution. Use string instead of number in result. Just like following example that idString.

[HttpGet]
        public IActionResult Get()
        {
            var obj = new { Id = long.MaxValue, IdString = long.MaxValue.ToString(), Name = "test" };
            return Ok(obj);
        }

At postman

image.png

At browser console.

image.png

Now it print same as it consider as string. This looks like small problem and mostly not occur during initial period of data but as data grow this will be a serious issue.

Hope this help.