Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need to use radix parameter when calling parseInt?

Tags:

javascript

What does radix actually means? Why do we need it?

parseInt(10, radixValue);  
like image 272
John Cooper Avatar asked Jul 07 '11 14:07

John Cooper


People also ask

What will be the radix value of the parseInt () method when the string begins with 0?

If the input string , with leading whitespace and possible + / - signs removed, begins with 0x or 0X (a zero, followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexadecimal number. If the input string begins with any other value, the radix is 10 (decimal).

What is the radix argument in Java?

Java parseInt(String s, int radix) method is the part of the Integer class of the java. lang package. This method is used to parse the string value as a signed decimal Integer object in the specified integer radix value passed as an argument.

What is the second parameter of parseInt in JavaScript?

The parseInt function accepts a second parameter known as redix . This parameter specifies what number system to use. If the redix is omitted then 10 is taken as the default. This is usually an integer between 2 and 36.

What is radix integer?

In a positional numeral system, the radix or base is the number of unique digits, including the digit zero, used to represent numbers. For example, for the decimal/denary system (the most common system in use today) the radix (base number) is ten, because it uses the ten digits from 0 through 9.


1 Answers

You might not always want to parse the integer into a base 10 number, so supplying the radix allows you to specify other number systems.

The radix is the number of values for a single digit. Hexidecimal would be 16. Octal would be 8, Binary would be 2, and so on...

In the parseInt() function, there are several things you can do to hint at the radix without supplying it. These can also work against you if the user is entering a string that matches one of the rules but doesn't expressly mean to. For example:

// Numbers with a leading 0 used a radix of 8 (octal) before ECMAScript 5. // These days, browsers will treat '0101' as decimal. var result = parseInt('0101');  // Numbers that start with 0x use a radix of 16 (hexidecimal) var result = parseInt('0x0101');  // Numbers starting with anything else assumes a radix of 10 var result = parseInt('101');  // Or you can specify the radix, in this case 2 (binary) var result = parseInt('0101', 2); 
like image 188
Justin Niessner Avatar answered Oct 13 '22 06:10

Justin Niessner