Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

How to calculate compound interest in Kotlin

1 Answer

0 votes
fun calculateCompoundInterest(principal: Double, rate: Double, years: Double): Double {
    // Validate input: all values must be non-negative
    if (principal < 0 || rate < 0 || years < 0) {
        println("Error: Principal, rate, and years must be non-negative values.")
        return -1.0
    }

    // Calculate total amount using the compound interest formula
    val amount = principal * Math.pow(1 + rate / 100, years)

    // Return compound interest (total amount - principal)
    return amount - principal
}

fun main() {
    val principal = 100_000.0
    val rate = 3.5
    val years = 5.0

    val compoundInterest = calculateCompoundInterest(principal, rate, years)

    if (compoundInterest >= 0) {
        println("Principal Amount: \$%.2f".format(principal))
        println("Annual Interest Rate: %.2f%%".format(rate))
        println("Years: %.2f".format(years))
        println("Compound Interest: \$%.2f".format(compoundInterest))
        println("Total Amount: \$%.2f".format(principal + compoundInterest))
    }
}



  
/*
run:

Principal Amount: $100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: $18768.63
Total Amount: $118768.63

*/

 



answered Aug 30, 2025 by avibootz

Related questions

...