Write two methods to output data num exactly to the nth position after the decimal point. The specific content is as follows
1. With the help of Math.pow(10,n);
2. With the help of ..toFixed(n) (JS 1.5 (supported by IE5.5+, NS6+ or above).
Test the output result of pi=3.14159265:
Accurately reach n digits after the decimal point, with the help of Math.pow(10,n):
3.1
3.14
3.142
3.1416
Accurately reach n digits after the decimal point, with the help of...toFixed(n):
3.1
3.14
3.142
3.1416
<html><head> <title>Rounding</title> <meta charset="utf-8"></head><body><script>function round_1(num,n){//Return the number num, accurate to n bits after the decimal point var number= Math.round(num*Math.pow(10,n)); return number/Math.pow(10,n);}function round_2(num,n){//Return the number num, accurate to n bits after the decimal point return num.toFixed(n); //JS 1.5(IE5.5+, supported by NS6+ and above)}var pi= 3.14159265;document.write("Exactly to n positions after the decimal point, with the help of Math.pow(10,n):<br>");for (var i=1; i<5; i++)document.write(round_1(pi,i) + "<br>"); document.write("Exactly to n positions after the decimal point, with the help of...toFixed(n):<br>");for (var i=1; i<5; i++)document.write(round_2(pi,i) + "<br>");</script> </body></html>The above is all about this article, I hope it will be helpful for everyone to learn Javas programming.