We’ll first start by understanding the methods and tricks used to convert strings to integer and float numbers, or array of numbers and finally see practical examples with simple React, React Hooks and Vue.JS apps.
When passing React props to components, which expect numeral values, in the way we assign regular HTML properties i.e using the
" quotes, string to number conversion is one of the possible ways we pass the accurate values besides using prop types or passing props via curly braces. We'll see that by example later in the article.
However, developers have resorted to use other tricks and techniques, other than the built-in techniques for performance reasons.
Head back to your command-line interface and create a file named
convert.js, open it and add the following code:
const num = Number('2020'); console.log(num);
Next, go back to the terminal and run the
convert.js script with node if you have it installed in your development machine:
If you don't have node installed on your system, you can also use your browser to run this code. Simply go to DevTools and write the code in the console and press Enter to run it.
Number is JS object that can wrap other objects and provides many built-in methods. Don’t use the constructor i.e
new Number("2020") since this will return a Number object instead of a number value.
parseInt() method that converts a string into a corresponding integer. It takes two arguments. The first argument is the string to convert and the second argument is the numeral base.
Go back to the
convert.js file and add the following code:
let year = "2020"; let iyear = parseInt(year, 10); console.log(iyear);//2020
parseInt() method takes two arguments, the first argument is the string to parse to an integer and the second argument is the radix or the numeral base, if you are not familiar with this mathematical notion, simply use the ten radix to convert the number to the format used by humans for doing the calculation. There are also other common bases such as 2 for the binary systems used by computers or 16 for the hexadecimal system also mostly used in computer tools.
parseFloat() that converts a string into a float number:
const pieStr = "3.14"; typeof pieStr "string" const pie = parseFloat(pieStr, 10); typeof pie "number"
This method will parse the string into a float number in the base 10 numeral system.
Continue reading this article.