Math.abs()
We can remove the sign part of the data and display the absolute value by using abs function. Here is the syntax
Math.abs(x);
Sample code is here
<script language='JavaScript' type='text/JavaScript'>
<!--
document.write(Math.abs(-5)); // output is 5
document.write("<br>");
document.write(Math.abs(5.56)); // output is 5.56
document.write("<br>");
document.write(Math.abs(-2.5)); // output is 2.5
document.write("<br>");
document.write(Math.abs(-1.355)); // output is 1.355
document.write("<br>");
//-->
</script>
abs() math function can also be used with other calculations
document.write(Math.abs(43-64)); // output is 21
We can integrate a demo script to calculate the absolute value of any integer.
Demo of Math.abs function
Here is the code
<script type="text/javascript">
function disp_data(){
var a1 = document.getElementById('t1').value;
a1=Math.abs(a1);
document.getElementById("a2").innerHTML= a1;
}
</script>
<input type=text name=t1 id='t1' value=-12.78><input type=button value='Display rounded number' onClick='disp_data()';>
<div id='a2' style=" background-color: #c0f0c0; width:200" > Enter a number</div>
Log value of a number →
←JavaScript Math Reference
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
plus2net.com
Math Functions in JavaScript