📅  最后修改于: 2023-12-03 14:44:48.041000             🧑  作者: Mango
Sometimes we need to round a number in JavaScript to a certain number of decimal places or to the nearest integer. There are a number of ways to achieve this using built-in JavaScript functions.
To round a number to a certain number of decimal places, we can use the toFixed()
method. This method rounds the number to the specified number of decimal places and returns a string.
let num = 3.14159265359;
let roundedNum = num.toFixed(2); // 3.14
In this example, we round the number num
to 2 decimal places using the toFixed()
method and assign the result to the variable roundedNum
.
To round a number to the nearest integer, we can use the Math.round()
method. This method rounds the number to the nearest integer and returns it as a number.
let num = 3.5;
let roundedNum = Math.round(num); // 4
In this example, we round the number num
to the nearest integer using the Math.round()
method and assign the result to the variable roundedNum
.
To truncate a number to a certain number of decimal places, we can multiply the number by a power of 10, truncate the result using the Math.trunc()
method, and then divide by the same power of 10.
let num = 3.14159265359;
let truncatedNum = Math.trunc(num * 100) / 100; // 3.14
In this example, we truncate the number num
to 2 decimal places by multiplying it by 100, truncating the result using the Math.trunc()
method, and then dividing by 100.
Rounding numbers in JavaScript is a common operation that can be performed using a variety of methods. By understanding these methods, we can write more efficient and accurate code.