Get square Root of any Number in JavaScript

0 6,778

in this article, we are going to learn how to get the square root of any number in JavaScript. in javascript, we are using Math.sqrt to get square of any number. if the value of a number in negative Math.sqrt returns NAN. So let’s start how to get the square root of any number with the help of JavaScript.

Creating Index Page

in this step, we are going to create a form where you can type any number and get square root with the help of javascript function. and also use internal CSS to design better form and button. You can simply copy the below source code and save it as index.html in your project folder.

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
		<title>Get square Root of any Number in javaScript</title>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
		<style>
			body{
				margin-top:95px;
			}
			.button {
				background-color: #4CAF50; /* Green */
				border: none;
				color: white;
				padding: 15px 32px;
				text-align: center;
				text-decoration: none;
				display: inline-block;
				font-size: 16px;
				
			}
			
			.button:hover {
				box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
			}
			
			input[type=number] {
				background-color: #3CBC8D;
				color: white;
				width:100%;
				align:center;
				height:35px;
			 }
			p{
			text-align:center;
			font-size:22px;
			}
			.well{
			background-color: #fafafa;
			box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
			}
	</style>
	</head>
<body>

	<div class="col-md-3"></div>
	<div class="col-md-6 well">
		<div class="col-md-2"></div>
		<div class="col-md-8">
			<div>
				<p>Enter Any number:</p>
				<input type="number" id="num" class="form-control"/><br />
				<center><button class="button" onclick="getSquareRoot()">Get Square Root</button></center>
				<br /><br />
				<div id="result"></div>
			</div>
		</div>
	</div>
<script src="js/script.js"></script>
</body>
</html>

Creating javascript function

in this step, we use Math.sqrt function to get the square root of a number. If the value of a number is negative, Math.sqrt returns NaN. copy the below source code and save it as script.js in your project folder and link properly with index.html.

function getSquareRoot(){
	var num = document.getElementById('num');
	if(num.value == ""){
		alert("Please enter a number first!");
	}else{
		var squareRoot = Math.sqrt(parseInt(num.value));
		document.getElementById('result').innerHTML = '<div class="alert alert-info">The Square Root of '+num.value+' is '+squareRoot+'</div>';
	}
}

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Source Code

Leave A Reply

Your email address will not be published.