AppDividend
Latest Code Tutorials

How To Convert A String To A Number In Javascript

219

Get real time updates directly on you device, subscribe now.

How To Convert A String To A Number In Javascript is today’s leading topic. We can use the Number object to convert the strings to a number. Also, there are other methods like parseInt() and parseFloat().

How To Convert A String To A Number In Javascript

Let us take an example of Javascript on Node.js.

Create one file called the node.js and add the following code.

const data = Number('48155');

console.log(data);

Now, go to the terminal and start the node.js server.

node server

It will also take care of decimal as well.

A Number is a wrapper object that can perform many operations. If we use the constructor (new Number("48155")) it returns us a Number object instead of a number value, so pay attention.

 

How To Convert A String To A Number In Javascript

#parseInt()

The parseInt() method converts a string into an integer (a whole number). It accepts two arguments. The first argument is the string to convert.

// server.js

let text = '21px';
let integer = parseInt(text, 10);

console.log(integer);

It will log the 21 value.

#parseFloat()

The parseFloat() method converts a string into a point number (a number with decimal points). You can even pass in strings with random text in them.

// server.js

let text = '3.14pie';
let integer = parseFloat(text, 10);

console.log(integer);

+ Unary Operator

One “trick” is to use the unary operator + before the string. The unary plus is used when your string is already in the form of an integer.

// server.js

let x = 5+"1000";

console.log(x);

The output will be the 51000.

#Math.floor()

Similar to the + unary operator, but returns the integer part.

// server.js

let floor = Math.floor("1000.51");
console.log(floor);

If your string is or might be a float and you want an integer then it might help you. 

The answer of above is 1000.

#Browser Compatibility

All three methods work in all modern browsers, and IE6 and up.

Finally, How To Convert A String To A Number In Javascript example tutorial is over.

 

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.