Javascript variable with leading zeroes - Stack Overflow

Javascript behaves differently with values having leading zeroes.alert(b) - prints different value.var

Javascript behaves differently with values having leading zeroes. alert(b) - prints different value.

var a = 67116;
var b = 00015;
alert(a);
alert(b);

I am more interested to know What conversion is applied here by javascript inside alert(b) ? (If i have them in double quotes. They work fine.)

Javascript behaves differently with values having leading zeroes. alert(b) - prints different value.

var a = 67116;
var b = 00015;
alert(a);
alert(b);

I am more interested to know What conversion is applied here by javascript inside alert(b) ? (If i have them in double quotes. They work fine.)

Share Improve this question edited Sep 9, 2014 at 15:17 tshepang 12.5k25 gold badges97 silver badges139 bronze badges asked Jun 14, 2013 at 17:39 KrishnamKrishnam 8491 gold badge15 silver badges21 bronze badges 4
  • Yeah, what the hell is going on here: jsfiddle/watson/4qsvQ – dezman Commented Jun 14, 2013 at 17:42
  • If they are in quotes, it is a string and will be read literally. – dezman Commented Jun 14, 2013 at 17:45
  • @Kris , your nickname is the same of my exgf, i'm depressed now :/ ... is that weird? – Jon Commented Jun 14, 2013 at 17:57
  • 1 May be you are too weird...i better say, you are her EX. i rather place you in variable b..that will give you new decimal life. – Krishnam Commented Jun 14, 2013 at 18:14
Add a ment  | 

3 Answers 3

Reset to default 3
var b = 00015

is an octal number

see this question for solution

A leading 0 makes the value an octal literal, so the value you put will be interpreted as a base 8 integer.

In other words, 015 will be equivalent to parseInt('15', 8).

As the other answers said, the leading zeroes make the number an octal literal. The decimal representation of the octal "15" is "13".

Note that there is no reason to use leading zeroes on number literals unless you really really want them to be interpreted as octals. I mean, don't use var b = 00015. If you're getting that value from user input, then it will be a string (i.e. "00015"), and you can convert to a decimal number with parseInt:

var b = "00015"; // or var b = document.getElementById('some_input').value
var numB = parseInt(b, 10); // 15

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742312454a4420166.html

相关推荐

  • Javascript variable with leading zeroes - Stack Overflow

    Javascript behaves differently with values having leading zeroes.alert(b) - prints different value.var

    13小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信