📜  number round - Javascript (1)

📅  最后修改于: 2023-12-03 14:44:48.041000             🧑  作者: Mango

Number Round - Javascript

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.

Round to Decimal Places

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.

Round to Nearest Integer

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.

Truncate Decimal Places

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.

Conclusion

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.