Kotlin kotlin.math.round
Round to the nearest whole unit using the even neighbour at an exact halfway point.
A simple example
kotlin.math.round
- Start with 2.5
- Do this Round a tie to an even integer
- Result 2
fun main() {
println(kotlin.math.round(2.5))
}
2.0
Syntax
kotlin.math.round(kilograms)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarRound a scale reading at an exact tie
A parcel scale sits exactly halfway between two display values. The warehouse needs a consistent tie rule so repeated weighings follow the same rounding convention.
fun main() {
val kilograms = 4.5
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (kotlin.math.round(kilograms)).toDouble())
}
4.000
A reading of 4.5 is halfway between 4 and 5. The even neighbour is 4.
Apply ties-to-even to a parcel scale
A parcel scale reports a value exactly between neighboring whole units. Compare how a tie is resolved on the display when the nearest even value lies on a different side of the measurement.
fun main() {
val weight = 5.5
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (kotlin.math.round(weight)).toDouble())
}
6.000
At an exact tie between five and six the even neighbour is six.
Round a parcel reading for a whole-unit display
A mailroom display shows only whole grams while its scale records tenths. A parcel weighs 18.7 grams and the display rounds to the nearest gram.
The reading lies closer to nineteen than eighteen.
What to watch for
Rounding rules differ between APIs. Check the rule for negative values and halfway cases.