Blog

method

JS

What does parseInt do?

Learning parseInt with fun examples ๐ŸŽ‰

Karthick V

Karthick V

Oct 8, 2022 โ€” Updated Dec 8, 2022 ยท 2 min read

  1. parseInt() method parses a string to an integer based on a specified radix number in 2nd argument.
  2. It only parses the very first string, any white spaces in between will be considered the end of the parsing.
  3. The return type is an Integer where the decimals are ignored.
  4. The second argument (optional) is based on the radix number system

A radix parameter specifies the number system to use mainly of four systems

  • Binary system specified as 2
  • Octal number system specified as 8
  • Decimal number system specified as 10
  • Hexadecimal number system specified as 16

_18
const number = "5";
_18
console.log(number + 5); // "55"
_18
parseInt(number + 5); // 55
_18
// parsing defaults to Decimal(10)
_18
_18
const number = "5.5";
_18
console.log(number + 5); // "5.55"
_18
parseInt(number + 5); // 10
_18
// The decimal will be ignored
_18
_18
const input = "53abc";
_18
console.log(number + 5); // "53abc5"
_18
parseInt(number) + 5; // 58
_18
// The value "abc" is not a number and js will ignore them
_18
_18
// Tricky one ๐ŸŽƒ
_18
parseInt("-0XF"); // -15
_18
// parsing defaults to hexadecimal since begins with `0x`


_16
const input = "5 3abc";
_16
console.log(number + 5); // "5 3abc5"
_16
parseInt(number + 5); // 10
_16
// Because the white space after 5 will be considered the end
_16
_16
parseInt("100", 2); // 4
_16
// Takes binary number system.
_16
_16
parseInt("100", 8); // 64
_16
// Considers octal number system.
_16
_16
parseInt("100", 10); // 100
_16
// Which is the decimal number system and the default radix parameter as well
_16
_16
parseInt("100", 16); // 256
_16
// 16 belongs to the hexadecimal number system.

@ragavkumarv
swipe to next โžก๏ธ