2

I have written a very simple JS program which is not giving expected output.

JSFiddle link: JsFiddle link

var p = {
        11735: [{
            d: 46.0,
            z: 06810
        }, {
            d: 30.6,
            z: 07047
        }, {
            d: 36.5,
            z: 07026
        }, {
            d: 36.9,
            z: 07032
        }, {
            d: 43.4,
            z: 07083
        }, {
            d: 32.9,
            z: 07094
        }, {
            d: 35.8,
            z: 07002
        }, {
            d: 39.6,
            z: 06460
        }, {
            d: 43.2,
            z: 06484
        }, {
            d: 15.0,
            z: 11581
        }, {
            d: 48.1,
            z: 07753
        }, {
            d: 37.9,
            z: 06614
        }, {
            d: 27.2,
            z: 10601
        }, {
            d: 0.0,
            z: 11735
        }]
    };
alert(p[11735][1].z);

Expected output should be 07047 but actual output is 3623

I don't know why is it happening. Please help me understand this.

1 Answer 1

3

07047 is interpreted as a base 8 number since it begins with a 0.

07047 (base 8) === 3623 (base 10)

http://www.unitconversion.org/numbers/base-8-to-base-10-conversion.html

If you want 07047 to be the number 7047 in base 10, then simply remove the 0 at the beginning.

Sign up to request clarification or add additional context in comments.

9 Comments

@Pavan do you understand the issue now?
@Jack that will not work in this case, because by the time parseInt() is called it'll be too late.
@Pointy good point, I suppose he could have them stored as strings and then call parseInt, but if he has access to the data source then he might as well remove the leading 0.
you can pass parseInt() a number and it will convert the value to a string for you so you don't have to store them as strings if you don't want to. parseInt(41, 16) == 65 works just as well as parseInt('41', 16) == 65
@MaxWorg You can pass it a number, but the problem in this case is that the number in the p object will already have been converted because of the leading zero so it is as pointy mentioned too late.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.