How can I format a number with 3 decimals in JavaScript?

I’m working with numbers stored in a database, and they have six digits after the decimal point. However, I only want to display these numbers with 3 decimals in my JavaScript application. What’s the best way to format these numbers to achieve this?

You can use the toFixed method in JavaScript to format numbers with a specific number of decimals. Here’s an example:

parseFloat(3.10391).toFixed(3);

Here parseFloat method converts a string to float, you might get the number from the database as a string. The toFixed method rounds the number to your defined decimal number places, and the result returns as a string with the formatted number.

Here are a few more options you can check, test, and use as you need.

(Math.round(3.10391 * 100) / 100).toFixed(3);

or

(Math.floor(3.10391 * 100) / 100).toFixed(3);

or

(Math.ceil(3.10391 * 100 ) / 100).toFixed(3);