1

I have this

   var checkBox = e.target;

    var tableRow = checkBox.parentNode.parentNode;
    var key = tableRow.attributes["key"];
    var aKey = key.nodeValue;

at this point aKey = "[123]"

what the best way to return 123 as an int in javascript? note that aKey could just as likely be "[5555555555555555555]" so I can't just grab characters 2-4. I need something more dynamic. I was hoping this could be parsed as like a one element array, but I see this is not correct. This is really a dataKey for an Infragisitcs grid. Their support is not very helpful.

Thanks for any advice.

Cheers, ~ck in San Diego

1
  • Do your numbers really get that big? JavaScript does not have enough mantissa for you to reliable store such numbers. I just checked in Chome's console and 5555555555555555555 is stored as 5555555555555555000. Commented Jul 13, 2009 at 22:55

4 Answers 4

3

As long as your key fits into an int without overflowing, you could do

numericKey = parseInt(aKey.substr(1, aKey.length - 2))
Sign up to request clarification or add additional context in comments.

2 Comments

According to his second example, his numbers don't fit into an int. Not sure he will ever really get any numbers that big, though. He might have been exaggerating. :-)
If the numbers could have leading zeros, you should specify base 10 by passing 10 as the second argument to parseInt. Otherwise, it will be interpreted as an octal number.
2

I think if it's always in that format, you could safely use eval() to turn it into an array and get the first element.

var aKey = eval( key.nodeValue );
var nKey = aKey[0];

1 Comment

since it's a nodeValue, I don't like this option.
0

include

<script src="http://json.org/json2.js"></script>

Which will give you a JSON object on browser which do not have it, but will use the browser implementation when available.

Then

JSON.parse(aKey);

Which will give you the array.

Comments

0

Your 5555555555555555555 example exceeds the largest "integer" which can be reliably stored in JavaScript's IEEE-754 double precision floating-point format, which is 9007199254740992. Hopefully, you just made that crazy big number up and your integers don't get nearly that large.

If you really do get numbers that big, you may need to keep your number in a string, break large numbers into multiple parts, or use a bigint library.

Comments

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.