This content originally appeared on Go Make Things and was authored by Go Make Things
Today, we’re going to look at three techniques you can use convert strings into numbers with JavaScript. These methods can also be used to modify existing numbers.
Let’s dig in!
The parseInt()
method
You can use the parseInt()
method to convert a string into an integer (a whole number). The second argument, 10
, is called the radix
. This is the base number used in mathematical systems. For our use, it should always be 10
.
// returns 42
parseInt('42', 10);
// also returns 42
parseInt('42px', 10);
The parseFloat()
method
You can use the parseFloat()
method to convert a string into a point number (a number with decimal points).
// returns 3.14
parseFloat('3.14');
// also returns 3.14
parseFloat('3.14someRandomStuff');
// returns 3
parseFloat('3');
The Number()
object
You can use the Number()
object to convert a string to a number.
Sometimes it returns integer. Other times it returns a float. And if you pass in a string with random text in it, you’ll get NaN
, an acronym for Not a Number.
As a result of this inconsistency, it’s generally safer to use parseInt()
or parseFloat()
. If you know the format of the number you’d like, use those instead. If you want the string to fail with NaN
if it has other characters in it, though, Number()
may actually be a better choice.
// returns 123
Number('123');
// returns 12.3
Number('12.3');
// returns NaN
Number('3.14someRandomStuff');
Modifying existing numbers
The parseInt()
method can also be used to modify existing numbers. If you have a float number that should be an integer, you can pass it into the parseInt()
method.
// returns 3
parseInt(3.14);
You can also pass existing numbers into the parseFloat()
method, though it won’t add decimals to an integer. It gets returned out as-is.
// returns 42
parseFloat(42);
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-01-25T15:30:00+00:00) Three ways to convert strings to numbers (and modify existing numbers) with vanilla JavaScript. Retrieved from https://www.scien.cx/2022/01/25/three-ways-to-convert-strings-to-numbers-and-modify-existing-numbers-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.