js output data accurate to n bit code after decimal point

  • 2021-07-01 06:27:33
  • OfStack

Write two methods, which can output data num to the n bit after the decimal point, as follows

1. With the help of Math. pow (10, n);
2. With the help of... toFixed (n) (JS 1.5 (IE 5.5 +, NS 6 + and above).
Test the output of pi=3. 14159265:
To the n bit after the decimal point, by means of Math. pow (10, n):
3.1
3.14
3.142
3.1416
To the n bit after the decimal point, by means of.. toFixed (n):
3.1
3.14
3.142
3.1416


<html>
<head>
  <title>4 Shed 5 Into </title>
  <meta charset="utf-8">
</head>
<body>
<script>
function round_1(num,n){// Returns a number  num,  Accurate to the decimal point  n  Bit 
  var number= Math.round(num*Math.pow(10,n));
  return number/Math.pow(10,n);
}
function round_2(num,n){// Returns a number  num,  Accurate to the decimal point  n  Bit 
  return num.toFixed(n); //JS 1.5(IE5.5+,NS6+ Above versions support )
}
var pi= 3.14159265;
document.write(" Accurate to the decimal point  n  Bit ,  With the aid of  Math.pow(10,n):<br>");
for (var i=1; i<5; i++)
document.write(round_1(pi,i) + "<br>"); 
document.write(" Accurate to the decimal point  n  Bit ,  With the aid of  ..toFixed(n):<br>");
for (var i=1; i<5; i++)
document.write(round_2(pi,i) + "<br>");
</script> 
</body>
</html>

The above is the whole content of this paper, hoping to help everyone learn javas programming.


Related articles: