WhyAlwaysMe
WhyAlwaysMe

Reputation: 41

How can I remove the decimal parts from numbers in Kotlin?

I'm using OpenWeatherMaps API for a weather app, but it shows decimal in some cities, how can I remove decimal parts from them?

override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            try {
                val jsonObj = JSONObject(result)
                val main = jsonObj.getJSONObject("main")
                val temp = main.getString("temp")+"°C"
                findViewById<TextView>(R.id.temp).text = temp

Upvotes: 2

Views: 10949

Answers (6)

Shroud
Shroud

Reputation: 420

If you want to remove the fractional portion of the number in a string, try something like

    val df = DecimalFormat("#")
    println("Foobar: ${df.format(100.10)}")

Result:

Foobar: 100

Upvotes: 0

Mehul Kabaria
Mehul Kabaria

Reputation: 6632

toInt() is solution of your question

val jsonObj = JSONObject(result)
                val main = jsonObj.getJSONObject("main")
                val temp =  +"${main.getString("temp").toDouble().toInt()}°C"
                findViewById<TextView>(R.id.temp).text = temp

Upvotes: 4

Muhammad Usman Butt
Muhammad Usman Butt

Reputation: 545

try this

  val temp = String.format("%.0f",main.getString("temp")) +"°C"

Upvotes: -1

forpas
forpas

Reputation: 164214

If you want everything before the dot there is substringBefore():

val temp = main.getString("temp").substringBefore(".") + "°C"

Upvotes: 13

Leo Aso
Leo Aso

Reputation: 12513

Use getInt not getString.

val temp = main.getInt("temp") + "°C"

Upvotes: 0

Filip Pranklin
Filip Pranklin

Reputation: 345

Seeing that you are using getString() and assuming the data sent from the server is like "31.23", the first thing that comes to my mind is just to split the string using the dot as delimiter and use the first value:

val temp = main.getString("temp")split(".")[0] +"°C"

Upvotes: 0

Related Questions