Reputation: 41
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
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)}")
Foobar: 100
Upvotes: 0
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
Reputation: 545
try this
val temp = String.format("%.0f",main.getString("temp")) +"°C"
Upvotes: -1
Reputation: 164214
If you want everything before the dot there is substringBefore()
:
val temp = main.getString("temp").substringBefore(".") + "°C"
Upvotes: 13
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