Vivek Modi
Vivek Modi

Reputation: 7383

Why value null after converting in int in kotlin

Hey I am working in android kotlin. I am getting double value in the form of string from server. I am converting that value in Int and checking that value is not null using toIntOrNull(). But I am getting 0 all the time.

Value coming from server

"value": "79.00"

My Data class

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class Detail(
    val value: String? = null,
) : Parcelable {
    val valueInDouble by lazy {
        value?.toDoubleOrNull() ?: Double.NaN
    }
    val valueInInt by lazy {
        value?.toIntOrNull() ?: 0
    }
}

whenever I print the value of valueInInt in console it returns 0. I know that 0 is coming because of toIntOrNull() but my value is coming from server which is not null. But I don't understand why this is happening. Can someone guide me please?

Expected Output

79

Actual Output

0

Upvotes: 1

Views: 1659

Answers (1)

Tenfour04
Tenfour04

Reputation: 93922

If the String value has a decimal in it, it cannot be parsed as an integer, so toIntOrNull() will return null.

You should parse as a Double and then convert the Double to an Int based on whatever type of rounding is appropriate for your use case.

val valueInInt by lazy {
    value?.toDoubleOrNull()?.roundToInt() ?: 0
}

Upvotes: 4

Related Questions