Write a Kotlin Program to Round a Number to n Decimal Places

In Kotlin, you can round a number to n decimal places using the round() function.

This function takes a double value as input and returns the rounded value as a double.

Here’s an example code snippet that demonstrates how to round a number to n decimal places:

fun roundToNDecimalPlaces(number: Double, n: Int): Double {
    val factor = Math.pow(10.0, n.toDouble())
    return Math.round(number * factor) / factor
}

In the above code, the roundToNDecimalPlaces function takes two parameters: number and n. number is the number to be rounded, and n is the number of decimal places to round to.

The function first calculates a factor by raising 10 to the power of n. This factor is used to multiply the input number and round it to the nearest integer. The result is then divided by the factor to get the rounded number with n decimal places.

You can use this function to round any double value to n decimal places. For example, if you want to round the number 3.14159265359 to 3 decimal places, you can call the function like this:

val roundedNumber = roundToNDecimalPlaces(3.14159265359, 3)

The value of roundedNumber would be 3.142.

In conclusion, Kotlin provides a simple way to round a number to n decimal places using the round() function.

The above code snippet provides an example implementation of this function that you can use in your own Kotlin projects.