Truncate Decimal Numbers in JavaScript | No Rounding | JS Tips

When working with decimal numbers in JavaScript, you may need to truncate them to a certain number of decimal places without rounding. This can be achieved using the Math.trunc() method, which removes any decimal digits from a number without rounding it.

To truncate a number to a specific number of decimal places, you can multiply it by a power of 10, apply Math.trunc(), and then divide by the same power of 10. For example, to truncate a number to 2 decimal places, you can use the following code:

const num = 3.14159;
const truncatedNum = Math.trunc(num * 100) / 100;
console.log(truncatedNum); // 3.14

This code multiplies the original number by 100 to move the decimal point two places to the right, applies Math.trunc() to remove any decimal digits, and then divides by 100 to move the decimal point back to its original position.

By using this method, you can truncate decimal numbers in JavaScript without rounding them, which can be useful in a variety of applications.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information