tostring - JavaScript Detecting Octal Value at Different Scenario -
var x = 02345; var y = x.tostring(); alert(y);
i realized there problem converting leading zeroes number string in javascript using tostring() method.
as can see output of code above, output 1253
instead of supposedly 02345
.
if leading 0 removed, code work expected, why? happening code above can change work expected.
var x = 2345; var y = x.tostring(); alert(y);
edit : reason asked question because have 2 different codes work differently despite being similar. after reading question has nothing tostring() method, why first set of code below not detect number octal value second set of code does.
var num=window.prompt(); // num = 0012222 var str = num.tostring(); var result = [str[0]]; for(var x=1; x<str.length; x++) { if((str[x-1]%2 === 0)&&(str[x]%2 === 0)) { result.push('-', str[x]); } else { result.push(str[x]); } } alert(result.join('')); //outputs : 0-012-2-2-2
the other code :
function numberdash(num) { var stringnumber = num.tostring(); var output = [stringnumber[0]]; (var = 1; < stringnumber.length; i++) { if (stringnumber[i-1] % 2 === 0 && stringnumber[i] % 2 === 0) { output.push('-', stringnumber[i]); } else { output.push(stringnumber[i]); } } return output.join(''); } numberdash(0012222) // outputs : "52-6-6";
many javascript engines add octal numeric literals specification. leading 0 indicates octal (base 8). 2345
in base 8 (octal) 1253
in base 10 (decimal):
octal decimal ----- -------------------- 2 2 * 8 * 8 * 8 = 1024 3 3 * 8 * 8 = 192 4 4 * 8 = 32 5 5 ----- -------------------- 2345 1253
you can disable using strict mode. see §b.1.1 of specification. doing makes 02345
syntax error.
so it's nothing tostring
, it's 02345
in code isn't value expect.
re updated question:
why first set of code below not detect number octal value second set of code does
because in first code, you're not dealing number, you're dealing string. window.prompt
returns string, not number, if type in digits.
even if converted string number via number(num)
or +num
, rules runtime string->number conversion different rules parsing javascript source code.
Comments
Post a Comment