- Numbers
- Floating-point types
- Literal constants for numbers
- Numbers representation on the JVM
- Explicit number conversions
- Operations on numbers
- Division of integers
- Bitwise operations
- Floating-point numbers comparison
- Float Data type Usage and Type Conversion in Kotlin
- 1. Mentioning type explicitly
- 2. Number type is automatically inferred
- 3. Declaring and Initializing separately
- Float Datatype Example Program in Kotlin
- Sample Output
- Type conversion syntax and declaration
- Float type Conversion Example Program in Kotlin
- Sample Output
- Kotlin Data Types
- Read More Articles
Numbers
Kotlin provides a set of built-in types that represent numbers.
For integer numbers, there are four types with different sizes and, hence, value ranges:
9,223,372,036,854,775,807 (2 63 — 1)
When you initialize a variable with no explicit type specification, the compiler automatically infers the type with the smallest range enough to represent the value. If it is not exceeding the range of Int , the type is Int . If it exceeds, the type is Long . To specify the Long value explicitly, append the suffix L to the value. Explicit type specification triggers the compiler to check the value not to exceed the range of the specified type.
val one = 1 // Int val threeBillion = 3000000000 // Long val oneLong = 1L // Long val oneByte: Byte = 1
In addition to integer types, Kotlin also provides unsigned integer types. For more information, see Unsigned integer types.
Floating-point types
For real numbers, Kotlin provides floating-point types Float and Double that adhere to the IEEE 754 standard. Float reflects the IEEE 754 single precision, while Double reflects double precision.
These types differ in their size and provide storage for floating-point numbers with different precision:
You can initialize Double and Float variables with numbers having a fractional part. It’s separated from the integer part by a period ( . ) For variables initialized with fractional numbers, the compiler infers the Double type:
To explicitly specify the Float type for a value, add the suffix f or F . If such a value contains more than 6-7 decimal digits, it will be rounded:
Unlike some other languages, there are no implicit widening conversions for numbers in Kotlin. For example, a function with a Double parameter can be called only on Double values, but not Float , Int , or other numeric values:
fun main() < fun printDouble(d: Double) < print(d) >val i = 1 val d = 1.0 val f = 1.0f printDouble(d) // printDouble(i) // Error: Type mismatch // printDouble(f) // Error: Type mismatch >
To convert numeric values to different types, use explicit conversions.
Literal constants for numbers
There are the following kinds of literal constants for integral values:
- Decimals: 123
- Longs are tagged by a capital L : 123L
- Hexadecimals: 0x0F
- Binaries: 0b00001011
Octal literals are not supported in Kotlin.
Kotlin also supports a conventional notation for floating-point numbers:
You can use underscores to make number constants more readable:
val oneMillion = 1_000_000 val creditCardNumber = 1234_5678_9012_3456L val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E val bytes = 0b11010010_01101001_10010100_10010010
There are also special tags for unsigned integer literals.
Read more about literals for unsigned integer types.
Numbers representation on the JVM
On the JVM platform, numbers are stored as primitive types: int , double , and so on. Exceptions are cases when you create a nullable number reference such as Int? or use generics. In these cases numbers are boxed in Java classes Integer , Double , and so on.
Nullable references to the same number can refer to different objects:
All nullable references to a are actually the same object because of the memory optimization that JVM applies to Integer s between -128 and 127 . It doesn’t apply to the b references, so they are different objects.
On the other hand, they are still equal:
Explicit number conversions
Due to different representations, smaller types are not subtypes of bigger ones. If they were, we would have troubles of the following sort:
// Hypothetical code, does not actually compile: val a: Int? = 1 // A boxed Int (java.lang.Integer) val b: Long? = a // Implicit conversion yields a boxed Long (java.lang.Long) print(b == a) // Surprise! This prints «false» as Long’s equals() checks whether the other is Long as well
So equality would have been lost silently, not to mention identity.
As a consequence, smaller types are NOT implicitly converted to bigger types. This means that assigning a value of type Byte to an Int variable requires an explicit conversion:
All number types support conversions to other types:
- toByte(): Byte
- toShort(): Short
- toInt(): Int
- toLong(): Long
- toFloat(): Float
- toDouble(): Double
In many cases, there is no need for explicit conversions because the type is inferred from the context, and arithmetical operations are overloaded for appropriate conversions, for example:
Operations on numbers
Kotlin supports the standard set of arithmetical operations over numbers: + , — , * , / , % . They are declared as members of appropriate classes:
You can also override these operators for custom classes. See Operator overloading for details.
Division of integers
Division between integers numbers always returns an integer number. Any fractional part is discarded.
This is true for a division between any two integer types:
To return a floating-point type, explicitly convert one of the arguments to a floating-point type:
Bitwise operations
Kotlin provides a set of bitwise operations on integer numbers. They operate on the binary level directly with bits of the numbers’ representation. Bitwise operations are represented by functions that can be called in infix form. They can be applied only to Int and Long :
Here is the complete list of bitwise operations:
- shl(bits) – signed shift left
- shr(bits) – signed shift right
- ushr(bits) – unsigned shift right
- and(bits) – bitwise AND
- or(bits) – bitwise OR
- xor(bits) – bitwise XOR
- inv() – bitwise inversion
Floating-point numbers comparison
The operations on floating-point numbers discussed in this section are:
- Equality checks: a == b and a != b
- Comparison operators: a < b , a >b , a = b
- Range instantiation and range checks: a..b , x in a..b , x !in a..b
When the operands a and b are statically known to be Float or Double or their nullable counterparts (the type is declared or inferred or is a result of a smart cast), the operations on the numbers and the range that they form follow the IEEE 754 Standard for Floating-Point Arithmetic.
However, to support generic use cases and provide total ordering, the behavior is different for operands that are not statically typed as floating-point numbers. For example, Any , Comparable <. >, or Collection types. In this case, the operations use the equals and compareTo implementations for Float and Double . As a result:
- NaN is considered equal to itself
- NaN is considered greater than any other element including POSITIVE_INFINITY
- -0.0 is considered less than 0.0
Here is an example that shows the difference in behavior between operands statically typed as floating-point numbers ( Double.NaN ) and operands not statically typed as floating-point numbers ( listOf(T) ).
Float Data type Usage and Type Conversion in Kotlin
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) < //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
Kotlin Data Types
- Int Data type Usage and Type Conversion in Kotlin
- Float Data type Usage and Type Conversion in Kotlin
- Double Data type Usage and Type Conversion in Kotlin
- Byte Data type Usage and Type Conversion in Kotlin
- Short Data type Usage and Type Conversion in Kotlin
- Long Data type Usage and Type Conversion in Kotlin
- Char Data type Usage and Type Conversion in Kotlin
- Boolean Data type Usage and Type Conversion in Kotlin
- Number Data type Usage and Type Conversion in Kotlin
- String Data type Usage and Type Conversion in Kotlin
- Elvis Operator in Kotlin
Read More Articles
- Read Data Input using Scanner in Kotlin
- Declare Variables In Kotlin
- Double Data type Usage and Type Conversion in Kotlin
- print and println Data Output in Kotlin
- Arithmetic Operators (Mathematical Operators) in Kotlin
- Unary Operators (Sign, Inverts, Increment, and Decrement) in Kotlin
- Printing Variables and Values in Kotlin
- Float Data type Usage and Type Conversion in Kotlin
- Equality Operators (==, !=) and Referential equality Operators (===, !==) in Kotlin
- Long Data type Usage and Type Conversion in Kotlin
- Comparison Operators in Kotlin
- Byte Data type Usage and Type Conversion in Kotlin
- In Operator (in and !in) in Kotlin
- Is Operator (is and !is) in Kotlin
- Assignment Operators and Augmented Assignment Operators in Kotlin
- Read Data Input from Command Line in Kotlin
- Read String Data Input in Kotlin
- Indexed Access Operator [, ] in Kotlin
- Char Data type Usage and Type Conversion in Kotlin
- Elvis Operator (?:) in Kotlin
- Not Null Assertion(!!) Operator in Kotlin
- Logical Operators in Kotlin
- Safe Call Operator (?.) in Kotlin
- Boolean Data type Usage and Type Conversion in Kotlin
- Repeat and Its Usage in Kotlin