Convert Degrees to Radians in JavaScript

- 1 minute read

The below JavaScript snippet converts a given number in degrees to radians:

const toRadians = (degrees, precision = 2) => {
    return parseFloat(((parseFloat(degrees) * Math.PI) / 180).toFixed(precision));
};

The above toRadians functions accepts two parameters.

The first parameter, degrees, is required, and it is the number (float or integer) in degrees to convert to radians.

The second parameter, precision, is optional and is a number representing the number of decimal places the resulting radians value should have. It defaults to 2 if an alternative value is not specified.

Here is some example usage:

toRadians(45); // Returns 0.79

toRadians(45, 4); // Returns 0.7854

This snippet uses JavaScript’s built-in Math.PI property for pi, which has fifteen decimal places of precision.

Link to this section Converting radians to degrees

Here is a toDegrees snippet with the exact same functionality and usage, except that it converts from radians to degrees:

const toDegrees = (radians, precision = 2) => {
    return parseFloat(parseFloat(radians) * (180 / Math.PI).toFixed(precision));
};

Link to this section Conclusion

And that is how I go about converting between degrees and radians in JavaScript!