Real World Example

A UPI Payment Record

A payment app such as PhonePe or Google Pay stores each transaction with several data types: a Long for the amount in paise and the transaction id, a String for the UPI id, a Boolean for success and a Double for cashback percentage. Values that arrive from the server as text are converted carefully.

Example

Converting server values and displaying rupees from paise:

fun main() {
    val transactionId = 412_398_765_001L
    val payeeUpi = "swiggy@icici"
    val amountPaise: Long = 54_950           // ₹549.50
    val isSuccess = true
    val cashbackPercent = 2.5
    val statusCode = 'S'

    val rupees = amountPaise / 100
    val paise = amountPaise % 100
    println("Txn $transactionId to $payeeUpi")
    println("Amount: ₹$rupees.$paise")
    println("Success: $isSuccess ($statusCode)")

    val cashbackPaise = (amountPaise * cashbackPercent / 100).toLong()
    println("Cashback: ₹${cashbackPaise / 100}.${cashbackPaise % 100}")

    val retriesFromServer = "2"
    val retries = retriesFromServer.toIntOrNull() ?: 0
    println("Retries: $retries")
}

Output

Txn 412398765001 to swiggy@icici
Amount: ₹549.50
Success: true (S)
Cashback: ₹13.73
Retries: 2

Practice

Exercise: A rating arrives from an API as the text "4.36". Convert it to a Double, then print it rounded to the nearest whole number of stars using roundToInt().

Show answer
import kotlin.math.roundToInt

fun main() {
    val ratingText = "4.36"
    val rating = ratingText.toDouble()
    println("Stars: ${rating.roundToInt()}")   // Stars: 4
}