How to convert a degree to a compass direction in Kotlin

1 Answer

0 votes
/*
0°   → North
45°  → North-East
90°  → East
135° → South-East
180° → South
225° → South-West
270° → West
315° → North-West
*/

// degreesToDirection converts degrees into a compass direction.
fun degreesToDirection(degrees: Double): String {
    // Normalize degrees to (0, 360)
    val normalized = (degrees + 360) % 360

    // Define compass directions
    val directions = listOf(
        "North", "North-East", "East", "South-East",
        "South", "South-West", "West", "North-West"
    )

    // Each direction covers 45 degrees
    val index = ((normalized + 22.5) / 45).toInt() % 8
    // Alternative: val index = (((normalized / 45) + 0.5).toInt()) % 8

    return directions[index]
}

fun main() {
    val degrees = 120.0
    
    println("For $degrees degrees, Compass direction: ${degreesToDirection(degrees)}")
}



/*
run:

For 120 degrees, Compass direction: South-East

*/

 



answered Nov 24, 2025 by avibootz
...