如何使用 JavaScript 将四舍五入的数字格式化为 N 位小数?
使用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP