apikotlintextviewdoubledecimalformat

How do I reduce the digits of an incoming multi-digit decimal number from API in Kotlin?


I'm getting a price value from an API but it's a multi-digits decimal number like 0.4785835398457. I want to reduce this number to 3 or 4 digits number like 0.3234 and I'm showing that value in a TextView. So First, I have to form this value and second I need to convert it to String. I tried that DecimalFormat method like at onBindViewHolder part of my RecyclerAdapter.

override fun onBindViewHolder(holder: CoinListViewHolder, position: Int) {
    val df = DecimalFormat("#.###")
    df.roundingMode= RoundingMode.CEILING  //<-----Here 
    df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() }) // <----- And here
    holder.itemView.coinTicker.text= coinList[position].asset_id
    

    holder.itemView.setOnClickListener {
            listener.onItemClick(coinList, position)
    }

But it did not work. Please help me. Thanks in advance.


Solution

  • You can just use a string formatter that uses the number of decimal places you want:

    val number = 123.12345
    "%.3f".format(number).run(::println)
    
    >> 123.123
    

    That basically converts a float value (f) to a string, to three significant digits (.3). The format spec is here but it's a bit complex.


    As far as your code goes, this:

    df.format(coinList[position].price_usd.also { holder.itemView.coinPrice.text = it.toString() })
    

    is equivalent to this:

    val price = coinList[position].price_usd
    holder.itemView.coinPrice.text = price.toString()
    df.format(price)
    

    I'm assuming you want to format the price and then display it in the TextView (right now you're just formatting it and doing nothing with the result), which would be this:

    df.format(coinList[position].price_usd)
        .let { holder.itemView.coinPrice.text = it.toString() }
    

    i.e. do the format, and then do this with the result