Mahozad
Mahozad

Reputation: 24522

How to convert Double (or Float) to Byte (or Short) in Kotlin 1.4?

In Kotlin version 1.4 the functions toByte() and toShort() are missing for Float and Double data types. How to convert those to Short or Byte?

Upvotes: 0

Views: 1235

Answers (1)

Mahozad
Mahozad

Reputation: 24522

As the official docs state:

Conversions of floating-point numbers to Short and Byte could lead to unexpected results because of the narrow value range and smaller variable size.

So if you want to convert to Byte or Short, you should do two steps: first convert to Int (with toInt()) and then to the target type (e.g. toShort()).

For instance: myVar.toInt().toByte()

Upvotes: 2

Related Questions