2 Example(s) of JavaScript toPrecision function


Description :

ToPrecision will format a number till provided length. In the below example it will return 33 because we provided 2 in toPrecision.


JavaScript toPrecision function Example - 1
<!DOCTYPE html>
<html>
 <head>
    <title>Welcome to LearnKode - A code learning platform</title>
</head>
  <body>
<button onclick="convertToPrecision()">Display the  formatted number</button>
<p id="sample"></p>
<script>
function convertToPrecision() {
        var num = 33.371;
    document.getElementById("sample").innerHTML = num.toPrecision(2);
   }
</script>
      </body>
</html>

Output

Description :

ToPrecision will retun different result based on provided length.


JavaScript toPrecision function Example - 2
<!DOCTYPE html>
<html>
 <head>
    <title>Welcome to LearnKode - A code learning platform</title>
</head>
  <body>
 <button onclick="convertToPrecision()">Display the  formatted number</button>
<p id="sample"></p>
<script>
function convertToPrecision() {
   var num = 13.3714;
    var a = num.toPrecision();
    var b = num.toPrecision(2);
    var c = num.toPrecision(3);
    var d = num.toPrecision(10);
    var n = a + "<br>" + b + "<br>" + c + "<br>" + d;
     document.getElementById("sample").innerHTML = n;
   }
</script>
      </body>
</html>

Output