How to define number of decimals in Kotlin/JS and Kotlin/Wasm?
Asked Answered
C

2

8

Let's imagine something like this:

var num: Float = 0.0f
num = 2.4 * 3.5 / 3.8

num has several decimals, but I want only 2.

In JS I would use num.toFixed(2).

Other answers here suggest to use "%.2f".format(num) or num.format(2). The latter needs a custom extension function:

fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)

However, any of these options leads to a compiler error of "unresolved reference". I don't think it is a question of imports because the compiler would suggest it.

Is there an easy way to do this?

Croner answered 14/3, 2017 at 16:30 Comment(3)
Did I understand correctly that you try to compile Kotlin to JS?Heavenward
Yes, that is what they're doing.Barbarity
Related: https://mcmap.net/q/839817/-is-there-a-way-in-kotlin-multiplatform-to-format-a-float-to-a-number-of-decimal-places/8583692Punke
W
12

Kotlin standard library for JS doesn't have anything like Double.format yet, but you can implement it easily with aforementioned toFixed function available in javascript:

fun Double.format(digits: Int): String = this.asDynamic().toFixed(digits)
fun Float.format(digits: Int): String = this.asDynamic().toFixed(digits)

This works because Double and Float in Kotlin are represented with Number data type in JS, so you can call toFixed() function on instances of those types.

Wreathe answered 15/3, 2017 at 1:28 Comment(1)
Nice! That worked, thanks! However you mistake in call toFixed(), you have to call format(). So in my example would be num.format(2). To be said also that this also convert Float to String, so better called when have to print itCroner
P
0

For Kotlin/Wasm, this is how it can be done.
Note that the function return type should be kotlin.js.JsNumber:

val myValue = 0.12345f
val myValue2Decimals = roundTo2Decimals(myValue)
fun roundTo2Decimals(number: Float): JsNumber = js("number.toFixed(2)")
Punke answered 11/7 at 10:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.