English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program rounds a number to n decimal places

Kotlin Examples Comprehensive

In this program, you will learn how to round a given number to n decimal places in Kotlin.

Example1:Use formatting to round numbers

fun main(args: Array<String>) {
    val num = 1.34567
    println("%.4f".format(num))
}

When the program is run, the output is:

1.3457

In the above program, we use the format() method to print the given floating-point number num to4the decimal point.4f represents decimal places after4format positions can be printed.

This means that at most onlypointafterof 4positions (decimal places), f represents printing floating-point numbers.

Example2:Use DecimalFormat to round numbers

import java.math.RoundingMode
import java.text.DecimalFormat
fun main(args: Array<String>) {
    val num = 1.34567
    val df = DecimalFormat("#.###")
    df.roundingMode = RoundingMode.CEILING
    println(df.format(num))
}

When the program is run, the output is:

1.346

In the above program, we use the DecimalFormat class to round off the given number num.

We use the #pattern#.### format declaration. This means that we want num to the decimal point after3digit. We will also set the rounding mode to ceiling, which will cause the last given position to be rounded up to the next number.

Therefore, the1.34567rounded off to the decimal point after3digit will be printed1.346, the6The digit is the3Decimal places5The next number.

This is the equivalent Java code:Java Program to Round Off a Number to n Decimal Places.

Kotlin Examples Comprehensive