Tuesday, February 7, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home JavaScript

Quick Tip: How to Convert a String to a Number in JavaScript

learningcode_x1mckf by learningcode_x1mckf
September 7, 2022
in JavaScript
0
Quick Tip: How to Convert a String to a Number in JavaScript
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


You might also like

An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf

Mimic Javascript actions on identical element? – JavaScript – SitePoint

How To Hire a Professional JavaScript Developer and Find the Best … – Intelligent Living

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:



Source link

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf

by learningcode_x1mckf
February 6, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

An Introduction to Lodash and Its Benefits for JavaScript Developers  MUO - MakeUseOf Source link

Read more

Mimic Javascript actions on identical element? – JavaScript – SitePoint

by learningcode_x1mckf
February 6, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Mimic Javascript actions on identical element? - JavaScript  SitePoint Source link

Read more

How To Hire a Professional JavaScript Developer and Find the Best … – Intelligent Living

by learningcode_x1mckf
February 6, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How To Hire a Professional JavaScript Developer and Find the Best ...  Clever Residing Source link

Read more

How to Use Regular Expressions in JavaScript – MUO – MakeUseOf

by learningcode_x1mckf
February 6, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

How to Use Regular Expressions in JavaScript  MUO - MakeUseOf Source link

Read more

Web Development & JavaScript Trends in 2023 – Electronicsmedia

by learningcode_x1mckf
February 6, 2023
0
Google expands open source bounties, will soon support Javascript fuzzing too – ZDNet

Web Development & JavaScript Trends in 2023  Electronicsmedia Source link

Read more
Next Post
Finding and Fixing Code Bugs – Real Python

Finding and Fixing Code Bugs – Real Python

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

How to Get and Use the Current Time in Python – Real Python

How to Get and Use the Current Time in Python – Real Python

December 12, 2022
Cloud Java Developer (Senior) (0257)

Cloud Java Developer (Senior) (0257)

January 5, 2023
7 Steps to Product Market Fit. Deciding what to build is the most… | by Eric Elliott | JavaScript Scene | Oct, 2022

7 Steps to Product Market Fit. Deciding what to build is the most… | by Eric Elliott | JavaScript Scene | Oct, 2022

October 27, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • C++ Is TIOBE's Language Of The Year – iProgrammer
  • JobRunr, the Java Scheduler Library, Released Version 6.0 – InfoQ.com
  • An Introduction to Lodash and Its Benefits for JavaScript Developers – MUO – MakeUseOf

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?