settingsAccountsettings
Menusettings

Q: Convert grads to degrees in JavaScript

+2 votes

Land surveyors use grads (also known as gon, 400 grads in a full turn) in their documents. Grads are rather unwieldy though, so you need to write a JavaScript function that converts from grads to degrees.

In addition, your program needs to constrain the results within the range 0°≤x<360°, so if you arrive at a value like -15°, it needs to be converted to 345° and 420° becomes 60°.

The input comes as single number.

Examples:

Input:
100

Output:
90


Input:
400

Output:
0


Input:
850

Output:
45


Input:
-50

Output:
315


The output should be printed to the console.

asked in JavaScript category by user golearnweb

1 Answer

+1 vote

Here is the conversion:

function gradsToDegrees(input) {
    let grads = Number(input);

    grads = grads % 400;
    if (grads < 0) {
        grads += 400;
    }
    //or grads = grads < 0 ? 400 + grads : grads;
    let degrees = grads / 400 * 360;//or let degrees = grads*0.9
    console.log(degrees);
}

gradsToDegrees(400);

You can use the remainder (modulo) operator to get a value that is cyclic – it returns the same result for all input values with offset equal to the second parameter.

For instance: n % 10 will return 3 with values for n 3, 13, 23, 243, 1003 and so on.

answered by user andrew
...