NickJar Dev
NickJar Dev

Reputation: 53

how to round a number in kotlin

I used String.format() to round to the third decimal place. However this didn't work and I solved it using DecimalFormat. Is there anything I implemented wrong?

val value = 36.295f
Timber.e("format: ${"%.2f".format(value)}")

expect: 36.30 but result: 36.29

Upvotes: 5

Views: 8093

Answers (3)

Tohid Zamani
Tohid Zamani

Reputation: 92

remove f

val value = 36.295
Timber.e("format: ${"%.2f".format(value)}")

Upvotes: 0

laalto
laalto

Reputation: 152787

Due to floating-point inaccuracies, 36.295f is not exactly 36.295 but rather something like 36.294998. This is the explanation for the output you received.

I believe your best option is to increase the precision in the input to start with. Use double-precision floating point i.e. lose the f for single-precision floating point.

DecimalFormat by itself cannot add precision to imprecise numbers. For example, The RoundingMode.CEILING approach offered in another answer would e.g. round 36.294 to 36.3 which might not be what you wanted.

Upvotes: 4

Mohamed Bdr
Mohamed Bdr

Reputation: 975

Use this example to show you how to round:

import java.math.RoundingMode
import java.text.DecimalFormat

fun main(args: Array<String>) {
    val value = 36.295f
    val df = DecimalFormat("#.##")
    df.roundingMode = RoundingMode.CEILING

    println(df.format(value))
}

Output:
36.30

So for your code you can use:
df.format(value) as your value

Check this link for more details: Link.

Upvotes: 3

Related Questions