Float Data type Usage and Type Conversion in Kotlin

Definition

  • A float is a 32-bit number in Kotlin. Float number is tagged with "f" or "F"
  • The type can be either declared explicitly or the compiler itself has the ability to infer the type of the assigned value.
  • In JVM, the characteristics of this "Float" variable is derived from the characteristics of primitive type float of Java which has a non-nullable default value.

Syntax and declaration

Thus a Float value can be declared by 3 ways as mentioned below.

1. Mentioning type explicitly

val variable_name : Float = value

for example,

val number : Float = 100f

2. Number type is automatically inferred

val variable_name = value

for example,
//Number type is automatically inferred
val number = 100f

3. Declaring and Initializing separately

var variable_name : Float 
variable_name = value

for example

//Declaring and Initializing separately
var number:Float 
number = 100f

Float Datatype Example Program in Kotlin

// Float Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args:Array<String>) {
    //Assigning value to Float variable explicitly
    val a:Float = 22.8f
    //Assigned value is inferred automatically by compiler
    val b = 100.0f

    println("Value of a is $a")
    println("Value of b is $b")
}

Sample Output

Value of a is 22.8
Value of b is 100.0

Type conversion syntax and declaration

//String to Float Conversion 
val variable_name = "string".toFloat()

//Int and Double to Float Conversion 
val variable_name = int_variable.toFloat()

Float type Conversion Example Program in Kotlin

// Float Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args: Array < String > ) {
    //Conversion from String and Float type is inferred
    val num1 = "500".toFloat()

    //Conversion from String and Declaring an Float value immediately
    val num2: Float = "100".toFloat()

    val num3: Int = 1000
    //Conversion from Float
    val num4: Float = num3.toFloat()

    val num5: Double = 2000.31e0
    //Conversion from Double
    val num6: Float = num5.toFloat()

    //Print values after conversion
    println("String to Float : num1 Value : $num1")
    println("String to Float : num2 Value : $num2")
    println("Float Value : num3 Value : $num3")
    println("Float to Float : num4 Value : $num4")
    println("Double Value : num5 Value : $num5")
    println("Double to Float : num6 Value : $num6")
}

Sample Output

String to Float : num1 Value : 500.0
String to Float : num2 Value : 100.0
Float Value : num3 Value : 1000
Float to Float : num4 Value : 1000.0
Double Value : num5 Value : 2000.31
Double to Float : num6 Value : 2000.31