Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

How to convert a number 010 to a string "010"

While executing some random expressions in console, I just found that

010 + "" returning 8 (even 011,0100.. are returning results by considering octal number system)

What would I have to do if I want to convert a number 010 to a string "010"? Not only for 010 but for every similar numbers. I managed to find a kind of similar explanation for this here. But that is not explaining how to convert it into a exact string version.

Upvotes: 5

Views: 1487

Answers (5)

Prof. Bear
Prof. Bear

Reputation: 217

If you are looking to convert multiple similar numbers into strings, you could also build a simple function that will do the work when called:

function convertSomething(number) {
    var string = "" + number;
    return string
}

Then you can just call your conversion function whenever you need it.

Upvotes: 1

Dmitri Pavlutin
Dmitri Pavlutin

Reputation: 19130

Use the following code:

"0" + (010).toString(8)  // "010"
"0" + (0111).toString(8) // "0111"

And a more general solution:

function toStringOctal(number) {
  return "0" + number.toString(8);
}

toStringOctal(010) // return "010"

But notice that in strict mode octal notations 0<number> are not allowed.

Upvotes: 3

gurvinder372
gurvinder372

Reputation: 68433

Get a string first by invoking the toString() method with the base number which is 8 in this case

Number(010).toString(8); //outputs "10"

it works without wrapping in Number too,

010.toString(8); //outputs "10"

use this method to padd 0's if you know the length of original number

function pad(n,digits){return n<Math.pow(10, digits) ? '0'+n : n}

so

pad(Number(010).toString(8),3); //3 is the number of digits

Upvotes: 6

Cezary Daniel Nowak
Cezary Daniel Nowak

Reputation: 1174

In Javascript 010 is octal literal and converts to 8 in decimal literal. In fact, you should avoid it, as strict mode disallows to use it.

There is no way to distinguish between octal and decimal notation other than parsing function body string :)

Upvotes: 6

millerbr
millerbr

Reputation: 2961

var num = 10;
var string = "0" + num.toString();
console.log(string);//gives you "010"

As mentioned in the comments to this post, it won't convert 010 directly, but will build a string. Not the most elegant solution.

Upvotes: 1

Related Questions