Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Kotlin native way to format a float to a number of decimal places?

Most of the answers use Java (e.g. String.format) to get the job done, but I need a way to do this purely with Kotlin native to support multiplatform programming.

This means no using Java packages

Say a method like fun Float.toString(numOfDec: Int). I'd like the value to round e.g.:

35.229938f.toString(1) should return 35.2

35.899991f.toString(2) should return 35.90

like image 395
anabi Avatar asked Apr 15 '20 09:04

anabi


People also ask

How do you get a float number up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

If you want to return a float, but only to remove the trailing decimals use this:

fun Float.roundToDecimals(decimals: Int): Float {
    var dotAt = 1
    repeat(decimals) { dotAt *= 10 }
    val roundedValue = (this * dotAt).roundToInt()
    return (roundedValue / dotAt) + (roundedValue % dotAt).toFloat() / dotAt
}
like image 159
Bogdan Draghici Avatar answered Sep 21 '22 15:09

Bogdan Draghici