Home >>Javascript Programs >How to parse number from string in JavaScript

How to parse number from string in JavaScript

How to parse number from string in JavaScript?

This article will help you how to parse number from string in JavaScript.

This JavaScript code will help you how to get the number input from user, but the input will bw in form of string. JavaScript provides functions to easily transform a string to a number. These are parseInt(), parseFloat(), Math.floor(), Math.ceil().

Methods

  • .parseInt(): This method helps you to always returns an integer. It takes a string as a first argument, and a base to which that string will be converted.
  • .Math.ceil(): It helps you to floating point number.
  • .parseFloat(): This method helps you to return the float point number equivalent and takes a string as an argument.
  • Math.floor(): This method returns the nearest integer rounded down to the number and is used to floating point number.

Let's see how to code JavaScript to parse number from string.

Let's take an example of parseInt():

<!DOCTYPE HTML> 
<html> 
<body>
<p id="stuff"></p>
<button onclick="parsenum()">click</button> 
	<script> 
	function parsenum(){
	var input = prompt('Enter a number');
    var number = Number(input);
    document.getElementById('stuff').innerHTML= (parseInt(input));
	}
	</script> 
</body> 
</html>
Output:

 

Let's take an example of parseFloat():

<!DOCTYPE HTML> 
<html> 
<body>
<p id="stuff1"></p>
<button onclick="parsenum1()">click</button> 
	<script> 
	function parsenum1(){
	var input = prompt('Enter a number');
    var number = Number(input);
    document.getElementById('stuff1').innerHTML= (parseFloat(input));
	}
	</script> 
</body> 
</html>
Output:

 


No Sidebar ads