Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
400 views
in Technique[技术] by (71.8m points)

Javascript, why treated as octal

I'm passing as parameter an id to a javascript function, because it comes from UI, it's left zero padded. but it seems to have (maybe) "strange" behaviour?

    console.log(0000020948);  //20948
    console.log(0000022115);   //9293 which is 22115's octal 
    console.log(parseInt(0000022115, 10));  // 9293 which is 22115's octal
    console.log(0000033959);  //33959
    console.log(20948);  //20948
    console.log(22115); //22115
    console.log(33959); //33959

how can I make sure they are parsing to right numebr they are? (decimal)

EDIT:

just make it clearer:

those numbers come from the server and are zero padded strings. and I'm making a delete button for each one.

like:

function printDelButton(value){
          console.log(typeof value);  //output string 
  return '<a href="#" onclick="deleteme('+value+')"><img src="images/del.png"></a>'
}

and 

function printDelButton(value){
console.log(typeof value); //output numeric
    console.log(value);   //here output as octal .... :S
 }

I tried :

console.log(parseInt(0000022115, 10));  // 9293 which is 22115's octal

and still parsing as Octal

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you receive your parameters as string objects, it should work to use

 parseInt(string, 10)

to interpret strings as decimal, even if they are beginning with 0.

In your test, you pass the parseInt method a number, not a string, maybe that's why it doesn't return the expected result.

Try

 parseInt('0000022115', 10)

instead of

parseInt(0000022115, 10)

that does return 221115 for me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...