I am trying to pass a number to my JavaScript function, but actually a wrong value is getting passed. I am giving the entire code here:
<html>
<head>
<script type="text/javascript">
function test(num)
{
/*It should alert as 01004 or 1004 but to my surprise it's alerting as 516!*/
alert(num);
}
</script>
</head>
<body>
<a href="javascript:test(01004);">Test it!</a>
</body>
</html>
In the above code, instead of 01004, if I pass it as 10040 I am getting the correct value in the alert box.
Any idea about this strange case?
Thanks in advance.
-
You might rename this question to something more descriptive such as 'Why is this JavaScript numeric literal evaluating to an unexpected value?'Drew Noakes– Drew Noakes2009年01月12日 09:50:21 +00:00Commented Jan 12, 2009 at 9:50
4 Answers 4
A numeric literal that starts with a zero is interpreted as octal, so writing 01004 is exactly the same as writing 516.
Some other answers suggesting using parseInt inside the function to convert the octal value to decimal.
This wont help, as the numeric value 516 is passed to the function. If you ask parseInt to give you a base 10 interpretation back, you'll get 516!
The way to fix this is either to lose the leading zero, or if the zero is required, make it a string literal rather than a numeric, and use parseInt(num, 10) inside the function.
Comments
The leading zero is probably making it think the number is octal.
UPDATE: Thanks to @Paul Dixon for jogging my mind awake somewhat this morning. 01004 is a literal, so no amount of after-the-fact parsing, i.e., parseInt, is going to update the base of the number. You need to either strip the leading 0 in your code to make it 1004 (the easiest solution), or put quotes around the literal to make it a string before sending it to parseInt (which is more work for no reason I can see).
2 Comments
test, it is still broken. If I then wrap 01004 in quotation marks, e.g., test('01004'), it works.Congratulations, you are the one millionth customer to get tripped up by octal literals in a language descended from B (and hence C).
Your prize is to lead the pitchfork parade outside Ken Thompson's house.
1 Comment
Quote the number -> '01004'
EDIT: I see parseInt('01004', 10) works fine... I really don't know why parseInt(01004, 10) doesn't
EDIT2: Ok, thanks to Paul Dixon
8 Comments
Explore related questions
See similar questions with these tags.