
Convert the string of any base to integer in JavaScript?
Type conversion also refers as typecasting. It is the process of transferring data from one data type to another. Implicit conversion occurs when the compiler (for compiled languages) or runtime (for script languages such as JavaScript) automatically converts data types. The source code may also expressly need conversion.
JavaScript provides several methods for converting a string value to a number.
The decimals are handled by the Number() method as well.
The conversions made using the Number() function are listed below.
const count = Number('1234') //1234If we give comma to separate decimals in a number then it outputs NaN
Number('10,000') //NaNIgnores values for decimals
Number('10.00') //10string to number conversion
Number('10000') //10000parseInt()
When a string contains more than one integer, parseInt() extract the number from the string.
parseInt('10 lions', 10) //10If the string does not begin with a number, you will receive NaN. (Not a Number)
parseInt("I'm 10", 10) //NaNIf you separate decimals in a number, the result is as seen below.
parseInt('10.00', 10) //10
parseInt('10.000', 10) //10
parseInt('10.20', 10) //10
parseInt('10.81', 10) //10
parseInt('10000', 10) //10000Math.floor():
Is a method which returns the integer value.
Math.floor('10,000') //NaN
Math.floor('10.000') //10
Math.floor('10.00') //10
Math.floor('10.20') //10
Math.floor('10.81') //10
Math.floor('10000') //10000Code to convert a string of any base to an integer:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Convert String to Number</title> </head> <body> <script> const number="5"; console.log(typeof(number)); //string //METHOD 1: //Convert String to Number const conversion = Number(number); console.log(typeof(conversion)); //METHOD 2: //Convert String to Number const number1="5"; console.log(typeof(number1)); const s2n = parseInt(number1) console.log(typeof(s2n)); </script> </body> </html>