Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing the string "009" as integer in javascript?

how to parse 009 in javascript i need return value as 9 but it returns 0.
But when i parse 001 it returns 1.

var tenant_id_max = '3-009';
tenant_id_split = tenant_id_max.split("-");
var tenant_id_int = tenant_id_split[1];
var tenant_id_count = parseInt(tenant_id_int);
like image 898
Baskar Avatar asked Oct 05 '12 16:10

Baskar


People also ask

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.

Can we convert string to int in JavaScript?

To convert a string to an integer parseInt() function is used in javascript. parseInt() function returns Nan( not a number) when the string doesn't contain number. If a string with a number is sent then only that number will be returned as the output. This function won't accept spaces.

How do you parse a string in JavaScript?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

What is %d in js?

%d or %i for Number. %f for Floating points. %o for an Object. %j for an JSON.


1 Answers

Do

var tenant_id_count = parseInt(tenant_id_int, 10);

That's because a string starting with "0" is parsed as octal (which doesn't work very well for "009", hence the 0 you get) if you don't specify the radix.

From the MDN :

If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt.

The most important thing to remember is Always specify the radix.

like image 163
Denys Séguret Avatar answered Sep 27 '22 21:09

Denys Séguret