Menu
Coddy logo textTech

Formatted Output

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 45 of 93.

challenge icon

Challenge

Easy

In the previous lesson, you calculated the amount each person pays. Now, format the output to display the amount as a currency value with exactly 2 decimal places.

Use Kotlin's String.format() method to format the amountPerPerson value to 2 decimal places. The format specifier "%.2f" formats a number with exactly 2 digits after the decimal point.

Update your output to display the formatted amount with a dollar sign:

Welcome to Bill Split Calculator!
Each person pays: $[formattedAmount]

To format a Double value, use:

String.format("%.2f", value)

For example, if the inputs are 85.50, 15, and 3, the output should be:

Welcome to Bill Split Calculator!
Each person pays: $32.78

The calculation: tip is 12.825, total bill is 98.325, divided by 3 people equals 32.775, which formats to 32.78.

Input constraints: the bill and tip percentage are nonnegative, and the number of people is a positive integer. Numeric inputs are valid and finite.

Try it yourself

fun main() {
    // TODO: Write your code below to print the welcome message
    println("Welcome to Bill Split Calculator!")
    
    val billAmount = readLine()!!.toDouble()
    val tipPercentage = readLine()!!.toInt()
    val numberOfPeople = readLine()!!.toInt()
    
    val tipAmount = billAmount * tipPercentage / 100
    val totalBill = billAmount + tipAmount
    
    val amountPerPerson = totalBill / numberOfPeople
    
    println("Each person pays: $amountPerPerson")
}

All lessons in Fundamentals

Practice on your own: Kotlin playground