Round numbers with toFixed() only if necessary

Let’s start with an example:

<script>
    console.log( (2.5123213).toFixed(2) ); // Output: 2.51
    console.log( (2).toFixed(2) ); // Output: 2.00
</script>

As you can see, toFixed() method will always round the number to the specified amount of places even if it’s not necessary, because, for example, the number is an integer.

To avoid this, we can apply one simple trick: multiply the result by 1.

num.toFixed(3) * 1;

Examples:

<script>
    console.log( (2).toFixed(2) * 1 ); // Output: 2
    console.log( (5.51111).toFixed(2) * 1 ); // Output: 5.51
</script>