In JavaScript, there are lots of methods to transform between data types. We’ve already coated how to convert a number to a string. On this brief tutorial, we’ll take a look at how one can convert a string to a quantity in JavaScript.
There are lots of conditions the place a quantity is likely to be saved as a string. For instance, values obtained from a type component are all the time strings.
Usually, you’ll be able to deal with a JavaScript string that comprises a quantity (and solely a quantity) as if it had been a quantity, and JavaScript will carry out the string-to-number conversion for you mechanically. Nonetheless, typically it’s worthwhile to extract a quantity from a string, or train extra management over how the conversion is completed.
On this fast tip, we’ll cowl 3 ways to transform a string to a quantity.
Convert a String to a Quantity Utilizing Quantity
Probably the most direct approach to convert a string to a quantity in JavaScript is to make use of the built-in Quantity
constructor operate. For instance:
const str = "10"
console.log(str);
console.log(typeof str);
const quantity = Quantity(str);
console.log(quantity);
console.log(typeof quantity);
When logging the worth of str
and its kind within the console, the result’s 10
as a string and string
respectively. After changing it, the result’s 10
as a quantity and quantity
respectively.
You possibly can see the instance in motion within the following CodePen demo.
See the Pen
Convert a String to a Number with Number() by SitePoint (@SitePoint)
on CodePen.
Please notice that should you go a non-numeric string to a quantity, NaN will be returned.
Convert a String to a Quantity Utilizing parseInt() and parseFloat()
One other strategy is utilizing parseInt()
and parseFloat()
. As you’ll be able to inform, parseInt()
parses a string to an integer, whereas parseFloat()
parses a string to a quantity with decimal factors.
For instance:
const str = "10.9"
console.log(str);
console.log(typeof str);
const intNumber = parseInt(str);
console.log(intNumber);
console.log(typeof intNumber);
const floatNumber = parseFloat(str);
console.log(floatNumber);
console.log(typeof floatNumber);
Just like the primary strategy, when logging the worth of str
and its kind within the console, the result’s 10.1
as a string and string
respectively. Nonetheless, when parsing str
utilizing parseInt
, the worth of intNumber
turns into 10
and its kind is quantity
.
Alternatively, when parsing str
utilizing parseFloat
, the worth of floatNumber
turns into 10.1
as a quantity and its kind is quantity
.
You possibly can see the instance in motion within the following CodePen demo.
See the Pen
Convert String to Number with parseInt() and parseFloat() by SitePoint (@SitePoint)
on CodePen.
parseInt’s Second Argument
parseInt()
takes a second argument that specifies the bottom of the quantity to be parsed from the string. This argument is the truth is optionally available, nevertheless it’s extremely suggest that you just all the time present it.
With out this second argument, parseInt
performs computerized radix detection. That’s, it detects the bottom of a quantity by its format within the string. A quantity starting 0x
or 0X
is taken into account to be hexadecimal (base 16), and all different numbers are thought-about to be decimal.
So, for instance, should you had been to name parseInt("08")
, the enter worth can be thought-about an octal quantity; however 8 shouldn’t be an octal digit (as a result of octal numbering is 0–7), so the operate would return a price of zero, not eight.
To keep away from any confusion, all the time specify the bottom when utilizing parseInt()
.
Convert a String to a Quantity Utilizing Unary Plus
The third approach to convert a string to a quantity is to make use of the unary plus (+
). If the unary plus is used earlier than an operand, it makes an attempt to transform it to a quantity. So, if the operand is a string that comprises a quantity, the unary plus will convert it to a quantity.
For instance:
const str = "10";
console.log(typeof str);
console.log(+str);
console.log(typeof +str);
While you log the kind of str
, as anticipated, it’s string
. Nonetheless, while you log the worth of +str
and its kind, 10
and quantity
are logged within the console respectively.
You possibly can see the instance in motion within the following CodePen demo.
See the Pen
Using Unary to Convert Strings by SitePoint (@SitePoint)
on CodePen.
Easy methods to Deal with Non-Numeric Characters in Strings
It’s necessary to take note of instances the place a string would possibly include characters aside from numbers and the way every strategy handles this.
When utilizing Quantity()
, if the string comprises characters aside from numbers, plus(+) and minus(-) indicators firstly, or decimal factors, the returned worth is the particular worth NaN (Not-a-Quantity). NaN is a world property that represents Not-a-Quantity. It’s returned by some numerical operations when the operands or parameters of these operations are both not numbers or can’t be used for that particular mathematical operation.
Alternatively, parseInt()
and parseFloat()
parse the string if the quantity is firstly of the string. It drops the remainder of the characters and takes the quantity encountered firstly of the string. Nonetheless, if the string begins with characters aside from numbers, plus(+) and minus(-) indicators firstly, or decimal factors, the returned worth is the particular worth NaN (Not-a-Quantity).
You possibly can see it in motion within the following CodePen demo.
See the Pen
Difference Between Number and parseInt by SitePoint (@SitePoint)
on CodePen.
As you’ll be able to see, Quantity()
returns NaN because the string comprises px
. Nonetheless, parseInt()
returns 10
because it’s firstly of the string.
You possibly can verify if a price is NaN utilizing the worldwide operate isNaN()
.
Conclusion
This brief tutorial has coated 3 ways to transform a string to a quantity in JavaScript. Quantity()
can convert a string to a quantity, whether or not it’s a float or an integer. Nonetheless, if the string comprises different characters, it returns NaN. That is useful if you wish to guarantee a strict conversion of the string.
Alternatively, parseInt()
and parseFloat()
are extra versatile approaches by way of dealing with different characters within the quantity. Nonetheless, these two capabilities can’t be used interchangeably in some instances. For instance, if the quantity within the string is a float and you utilize parseInt()
, you’ll get an incorrect worth in comparison with the string.
Though the unary is simple to make use of, it may cut back readability of your code. Whichever technique you select, it’s necessary to look out for instances the place the outcome returned is likely to be NaN.
For those who discovered this text helpful, you might also get pleasure from the next: