Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin-js: Define number of decimals

Tags:

kotlin

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 fun:

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 is a question of imports cause the compiler would suggest it.

Is there an easy way to do this?

like image 946
eloo Avatar asked Mar 14 '17 16:03

eloo


1 Answers

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.

like image 99
Ilya Avatar answered Nov 07 '22 15:11

Ilya