Sử dụng phương thức toFixed () để định dạng một số làm tròn thành N số thập phân. Phương thức toFixed () định dạng một số với một số chữ số cụ thể ở bên phải của số thập phân.
Ví dụ
Bạn có thể thử chạy đoạn mã sau để tạo thành một số được làm tròn thành N số thập phâ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> Đầu ra
num.toFixed() is : 15 num.toFixed() is : 15.00 num.toFixed() is : 15.0