简体   繁体   中英

angular.js parsing integer incorrectly

I'm using angular to make an AJAX call to my own REST API.

$scope.authenticate = function() {
    $http({
        headers: httpHeaders,
        url: '/something/',
        method: "POST",
        data: { 'userId' : $scope.userId, 'password': $scope.password },
        cache: false
    })
    .success(function(response, status) {
        console.log(response);
        var ourstring = JSON.stringify(response);
        console.log(ourstring);
        $scope.authenticate_data = response;
        $scope.sessionId = response.sessionId;
        $scope.cookie = response.cookie;
        $scope.message = "You have successfully authenticated."
    });
}

Somehow, angular incorrectly parses integers, and in the Chrome inspector's network tab, the call shows the following:

REQUEST TAB

{"sessionId": 115053508782199126, "cookie": "JSESSIONID=E61DD3443AE9E119060A637CF039936B; Path=/webservice"}

PREVIEW TAB (value stored in scope)

{"sessionId":115053508782199120,"cookie":"JSESSIONID=E61DD3443AE9E119060A637CF039936B; Path=/webservice"}

When I wrap the integer as a string in the backend, everything is fine. However, I really want to get understand what is causing this error.

Related link: Angular $resource does not parse correctly an integer response

There is no such thing as a purely integer variable in JavaScript.

Instead, all we have are Number s, which are stored as IEEE754 floating-point values . And from the ECMAScript standard , we have:

Note that all the positive and negative integers whose magnitude is no greater than 2^53 are representable in the Number type (indeed, the integer 0 has two representations, +0 and −0).

Note that this does not mean that the largest integer representable in JavaScript is 2^53, but rather that once you get larger than this, only some integers can be represented. Once you've exhausted the 53-bit mantissa of the IEEE754 floating point representation, there start to appear gaps between the integers.

Your example session ID 115053508782199126 is rather larger than 2^53 , and it turns out the closest integer floating-point value to it is 115053508782199120 . So, you need to use strings.

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