Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading