How to replace NaN value with 0, = Zero, != null in Kotlin for speed?

Viewed 884

When i start my app, which should get the speed of the device, i get a NaN( i think its for " not a number"?) value for 1- 3 seconds in the textfield.The numbers are safed in a repository, but if is Nan, the app crashes. How can i replace this NaN with 0(Zero)?... for ex.: If( NaNvalue = true){ (value = 0)}...something like that. I didnt find anything written in android or kotlin, just python(which i am not familiar with). Any help would be great!!! Thank you...

my code:

    fun getSpeed(location: Location): Float{
            if (mRunning ) {
            //    val getkmh = (location.speed * 3.6)
           //     mSpeedKmH = getkmh.toFloat()
                mElapsedSeconds = ((SystemClock.elapsedRealtime() 
                -mChrono!!.getBase()) / 1000)
                mSpeedMeter = mDistanceTotal/mElapsedSeconds.toFloat()
                mSpeed = (   mSpeedMeter *3.6).toFloat()// *3.6 > KmH
            }
            return mSpeedKmH
        }

   fun updateSpeed() {
        val speedMeter = String.format(Locale.getDefault(), "%.1f",mSpeed)
            tvSpeed.text = speedMeter
    }
3 Answers
val value: Double = yourDoubleValue.let { if (it.isNaN()) 0.0 else it}

The same can be applied to Float values

You can do it like the other answer shows or using takeIf and the elvis operator:

val speedMeter = String.format(Locale.getDefault(), "%.1f", mSpeed.takeIf { !it.isNaN() } ?: 0.0)

Thanks to Fernando and Tenfour04!!! Both versions are working!!

val speedGesammt = String.format(Locale.getDefault(), "%.1f", mSpeedAverageKmH.takeIf { !it.isNaN() } ?: 0.0)

val speedGesammt = String.format(Locale.getDefault(), "%.1f", mSpeedAverageKmH.let { if (it.isNaN()) 0.0 else it})

Related