1

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

2
  • That is because 0 is default value of an int or double Commented Mar 28, 2022 at 17:09
  • I know that default value is 0. But my value coming from server is 79.00 Commented Mar 28, 2022 at 17:19

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.