Categories
JavaScript Answers

How to truncate decimal numbers in JavaScript?

Spread the love

Sometimes, we want to truncate decimal numbers in JavaScript.

In this article, we’ll look at how to truncate decimal numbers in JavaScript.

How to truncate decimal numbers in JavaScript?

To truncate decimal numbers in JavaScript, we can use the Math.trunc method.

For instance, we write

const a = 5.467;
const truncated = Math.trunc(a * 100) / 100;

to call Math.trunc with the number a multiplied by 100 to truncate the number.

Then we divide the truncated number by 100 to return a truncated to 2 decimal places.

Conclusion

To truncate decimal numbers in JavaScript, we can use the Math.trunc method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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