使用toFixed()方法将舍入的数字格式化为N个小数。toFixed()方法格式化一个数字,该数字在小数点右边具有特定的数字位数。
您可以尝试运行以下代码以将数字四舍五入为N个小数-
<html> <head> <title>JavaScript toFixed() Method</title> </head> <body> <script> var num = 15; document.write("num.toFixed() is : " + num.toFixed()); document.write("<br />"); document.write("num.toFixed() is : " + num.toFixed(2)); document.write("<br />"); document.write("num.toFixed() is : " + num.toFixed(1)); document.write("<br />"); </script> </body> </html>
输出结果
num.toFixed() is : 15 num.toFixed() is : 15.00 num.toFixed() is : 15.0