How to Cut Decimals in JavaScript?

Estimated read time 1 min read

In JavaScript, you can cut decimals to a specified number of decimal places using the toFixed method of the Number object. Here’s an example that cuts a number num to a specified number of decimal places places:

const cutDecimals = (num, places) => {
  return Number(num.toFixed(places));
};

const num = 3.1415926535;
const cutNum = cutDecimals(num, 2);
console.log(cutNum);
// Output: 3.14

In this example, the cutDecimals function takes a number num and a number of decimal places places as arguments. The function then converts num to a string with a specified number of decimal places using the toFixed method, and then returns the result as a number using the Number constructor. The toFixed method rounds the number to the specified number of decimal places and adds zeros to the end if necessary to achieve the desired number of decimal places.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply