in

Quick Tip: How to Convert Strings to Numbers in JavaScript

1662517724convert number to string js

[ad_1]

In JavaScript there are many ways to convert data types. We have already seen how to convert numbers to strings. In this short tutorial, we’ll look at how to convert strings to numbers in JavaScript.

There are many situations in which numbers are stored as strings. For example, values ​​received from form elements are always strings.

In general, you can treat JavaScript strings that contain numbers (and only numbers) as if they were numbers, and JavaScript will automatically perform string-to-number conversions. However, sometimes you need to extract numbers from strings or have more control over how they are converted.

This quick tip describes three ways to convert strings to numbers.

Convert string to number using Number

The most direct way to convert strings to numbers in JavaScript is the built-in Number constructor function. for example:

const str = "10"
console.log(str); 
console.log(typeof str); 

const number = Number(str);
console.log(number); 
console.log(typeof number); 

When logging the value of str Its type in the console, the result is 10 as a string string Respectively. The result after conversion is 10 as a number number Respectively.

You can see a working example in the CodePen demo below.

look at the pen
Convert string to number using Number() by SitePoint (@SitePoint)
with a code pen.

Note that passing a non-numeric string for a number returns NaN.

Convert string to number using parseInt() and parseFloat()

Another approach is using parseInt() When parseFloat()As you can see, parseInt() parse the string to an integer, but parseFloat() Parse a string into a number with a decimal point.

for example:

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); 

Similar to the first approach, str Its type in the console, the result is 10.1 as a string string Respectively.However, when parsing str Use parseInt,The value of the intNumber become 10 and the type is number.

On the other hand, when parsing str Use parseFloat,The value of the floatNumber become 10.1 As a number, its type is number.

You can see a working example in the CodePen demo below.

look at the pen
Convert string to number using parseInt() and parseFloat() by SitePoint (@SitePoint)
with a code pen.

second argument to parseInt

parseInt() Takes a second argument that specifies the base of the number to parse from the string. Although this argument is actually optional, it is highly recommended that you always specify it.

Without this second argument, parseInt Performs automatic radix detection. That is, it detects the base of a number by its format in the string.number start 0x Also 0X is assumed to be a hexadecimal number (base 16), all other numbers are assumed to be decimal numbers.

So for example if you call parseInt("08"), the input value is assumed to be octal. However, 8 is not an octal number (because octal numbers are 0 through 7), so the function returns a value of 0 instead of 8.

To avoid confusion, always specify a base when using parseInt().

Convert string to number using unary plus

A third way to convert a string to a number is the unary plus (+). Using a unary plus before an operand will try to convert it to a number. So if the operand is a string containing a number, unary plus converts it to a number.

for example:

const str = "10";
console.log(typeof str); 
console.log(+str); 
console.log(typeof +str); 

When I log the type of stras expected, it is string. However, when I log the value of +str and its type, 10 When number Log in to each console.

You can see a working example in the CodePen demo below.

look at the pen
Convert string in SitePoint (@SitePoint) using unary
with a code pen.

How to handle non-numeric characters in strings

It’s important to consider when strings may contain non-numeric characters and how each approach handles this.

while using it Number(), if the string contains digits, leading plus (+) and minus (-) signs, or non-decimal characters, the value returned is the special value NaN (Not-a-Number). NaN is a global property representing not-a-number. Returned by numeric operations when the operands or parameters of these operations are not numeric or cannot be used for that particular mathematical operation.

on the other hand, parseInt() When parseFloat() Parse the string if the number is at the beginning of the string. Remove the remaining characters and get the number at the beginning of the string. However, if the string begins with digits, leading plus (+) and minus (-) signs, or non-decimal characters, the returned value is the special value NaN (Not-a-Number).

You can see it in action in the CodePen demo below.

look at the pen
Difference between Number and parseInt by SitePoint (@SitePoint)
with a code pen.

as you can see, Number() Returns NaN because it is in the string. px. but, parseInt() Return value 10 Because it is at the beginning of the string.

You can use a global function to check if a value is NaN. isNaN().

Conclusion

In this short tutorial, we’ve seen three ways to convert strings to numbers in JavaScript. Number() You can convert strings to numbers, whether they are floats or integers. However, it returns NaN if the string contains other characters. This is useful if you want to convert strings exactly.

on the other hand, parseInt() When parseFloat() It’s a more flexible approach in terms of handling other characters in the number. However, in some cases these two functions cannot be used interchangeably.For example, if the numbers in your string are floats and you use parseInt()I get the wrong value when compared to a string.

Unary is easy to use, but it can make your code less readable. Whichever method you choose, it’s important to note that the returned result can be NaN.

If you found this article useful, you may also enjoy:

[ad_2]

Source link

What do you think?

Leave a Reply

GIPHY App Key not set. Please check settings

    James Angus smsf

    Bluestone Home Loans Launches Home Loans for SMSF

    Screen Shot 2021 11 15 at 7.40.23 PM

    WordPress to drop security updates for versions 3.7 to 4.0 by December 2022 – WP Tavern