Search code examples
stringkotlinsplit

how to convert an integer number to decimal kotlin?


I am trying to convert cm to ft. I get cm in my convertion function and translate cm to ft. like this

val ftHeight = _height * 0.032808399

it works properly but ftHeight contains ft and inc together. I have to seperate ft and inc values because I show different textfields them.

I seperate ftHeight like this

val inc = ftHeight.toString().substringAfter(".")
val ft = ftHeight.toString().substringBefore(".")

but there is a problem for example I assume that ftHeight is equal 3.289812

so that

ft : 3

inc : 289812

when I try to calculate ft to cm I need to ft and inc values but the value of inc should not be like this

it should be like this for my calculatin

0.289812

How can I solve that issue? can you help me ?

hear is my calculation function

fun onCmToFtChange(_height: Int) {

        val ftHeight = _height * 0.032808399

        val inc = ftHeight.toString().substringAfter(".")
        val ft = ftHeight.toString().substringBefore(".")

        _viewState.update {
            it.copy(
                ft = ft,
                inc = "${inc[0]}",
                _ft = ft.toInt(),
                _inc = "0.{$inc}".toInt(). // this is incorrect code I just tryed something for this issue but it didnt work
            )
        }
    }

Solution

  • you can change the way you calculate inc, Instead of

    val inc = ftHeight.toString().substringAfter(".")
    val ft = ftHeight.toString().substringBefore(".")
    

    You can use:

    val ft = ftHeight.toString().substringBefore(".")
    val inc = ftHeight - ft.toInt()
    

    If you want to stick to your previous approach and convert string to Double, you can use:

    val inc = ftHeight.toString().substringAfter(".")
    val ft = ftHeight.toString().substringBefore(".")
    val _inc = "0.$inc".toDouble()