8

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);

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It means parse it as a bes 10 (decimal) number. Number strings starting with a 0 get parsed automatically as base 8

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.