Useful JS Snippets

A collection of Javascript snippets, that might help you achieve something more easily or faster

  • Tags: Web Development
  • Last updated: 

A toFixed function that does not convert to string

It is faster than casting to string and back to number.

// Does the same as `Number.prototype.toFixed` but without casting
// the return value to a string.
function toFixed(num, precision) {
    const pow = 10 ** precision;
    return Math.round(num * pow) / pow;
}

Credits go to Marvin Hagemeister