Skip to main content

How to Make a Calculator App

Copied to clipboard!
No boilerplate memorization required

How to Vibe Code a Native Calculator App

Stay in your creative flow. Direct AI models with high-level intent, generate a responsive Jetpack Compose keypad and expression engine, and ship an installed Calculator APK on your phone in under 20 minutes.

Core Stack

Kotlin Compose

Math Engine

BigDecimal / Parser

AI Partner

Claude / Gemini

Target Time

15โ€“20 Mins

The Philosophy

The Vibe Coding Mobile Philosophy

Traditional calculator tutorials bog beginners down with 20 separate XML button listeners, floating-point rounding bugs (0.1 + 0.2 = 0.300000004), and clunky state machines. Vibe coding flips the script. You act as the Product Director & Architect: specifying the tactile keypad layout, live expression preview, and calculation tape while conversational AI synthesizes a rock-solid single-file Compose app.

Old-School Mobile Stress

  • Manually aligning 20+ buttons in nested XML GridLayout or ConstraintLayout tags.
  • Debugging IEEE 754 floating-point precision glitches and chained operator bugs.
  • Crashing when a user taps รท 0 or presses . twice in the same number.
  • Writing repetitive boilerplate just to store a scrollable calculation history tape.

The Vibe Coder Way

  • Declarative Jetpack Compose grid that renders a 4x5 tactile keypad in 15 lines of Kotlin.
  • Describe the feel: "iOS/Braun-inspired tactile keypad with spring press animations and a live preview line."
  • Instruct AI to use BigDecimal math and guard multiple decimals or divide-by-zero cleanly.
  • Run and test on your physical phone over Wi-Fi in seconds.
Execution

The 4-Step Blueprint

From a blank Android Studio project to a tactile, history-aware calculator on your home screen.

Step 01

Spawning the Empty Compose Canvas

Open Android Studio and select New Project > Empty Activity (with Compose logo). Name it VibeCalc.

๐Ÿ’ก Pro Vibe Tip: Avoid legacy XML templates. Jetpack Compose lets you define the button grid, display readout, and expression evaluator in one self-contained file.
Step 02

The "One-Shot Architect" Prompt

Give your AI partner the complete spec upfront: a 4-column keypad grid, live running total below the active expression, and a scrollable history tape.

๐Ÿ”‘ Key Constraint: Tell the AI: "Put the entire UI and math evaluator inside a single MainActivity.kt with zero external math libraries."
Step 03

Tactile Styling & Micro-Interactions

Add haptic key clicks, scale-down button press animations, auto-shrinking display text for long numbers, and tap-to-reuse history rows.

โœจ Iteration Secret: Use Compose @Preview to fine-tune button corner radii and operator accent colors without re-running Gradle.
Step 04

Run on Your Real Phone

Enable Wireless Debugging on your Android handset, pair via QR code in Android Studio, and press Run (Shift+F10).

๐Ÿ† The Grand Payoff: You now have a custom, zero-ad calculator tailored with your favorite shortcuts and history tape right in your pocket.
Interactive Tool

Vibe Prompt Configurator

Customize your calculator's look, precision, and extra tools, then copy the master prompt into Claude, Gemini, or Cursor.

Special Feature Vibe
Optional custom details added straight into your master prompt.
Generated Master Prompt
Ready to paste into Claude, Gemini, or ChatGPT Single-file Compose ready
Product Spec

Essential Elements of a Calculator App

Whether you are building an everyday pocket utility or a scientific powerhouse, every great calculator app relies on these core foundations:

  • Clear & Intuitive Keypad Layout

    Logically grouped digit keys (0โ€“9, .), primary operators (+, โˆ’, ร—, รท), and utility actions (AC, โŒซ, %, ยฑ) with generous tap targets.

  • Dual-Line Expression Display

    Show both the full ongoing expression at the top and a live formatted result below so users never lose track of multi-step math.

  • High-Precision Math Engine

    Handle large numbers, decimals, and order of operations (PEMDAS) using exact decimal arithmetic without floating-point rounding glitches or divide-by-zero crashes.

  • Scientific & Advanced Operations

    Support square roots (โˆš), exponents (xสธ), parentheses, and trigonometric functions without cluttering the primary portrait keypad.

  • Calculation Tape & Memory

    Keep a scrollable history of previous equations and memory registers (M+, MR) so users can review or reuse earlier figures in one tap.

  • Built-In Unit & Currency Helpers

    Extend utility with quick converters for length, weight, tips, or currencies right alongside the standard calculator screen.

UX Checklist Before Shipping: Prevent consecutive operators (e.g., ++), block multiple decimal points in a single operand, and auto-scale font size when numbers exceed 10 digits.
Starter Template

The "Golden" Single-File Compose Template

Replace the contents of your MainActivity.kt with this to run a complete, history-enabled calculator right now.

app/src/main/java/.../MainActivity.kt
Kotlin + Compose
package com.example.vibecalc

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import java.math.BigDecimal
import java.math.RoundingMode

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme(
                colorScheme = darkColorScheme(
                    background = Color(0xFF0B0F17),
                    surface = Color(0xFF161F2E),
                    primary = Color(0xFFF59E0B)
                )
            ) {
                Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
                    VibeCalculatorScreen()
                }
            }
        }
    }
}

@Composable
fun VibeCalculatorScreen() {
    var currentInput by remember { mutableStateOf("0") }
    var previousInput by remember { mutableStateOf("") }
    var pendingOp by remember { mutableStateOf<String?>(null) }
    var resetNext by remember { mutableStateOf(false) }
    var history by remember { mutableStateOf(listOf<Pair<String, String>>()) }

    fun compute(aStr: String, bStr: String, op: String): String {
        val a = aStr.toBigDecimalOrNull() ?: return "Error"
        val b = bStr.toBigDecimalOrNull() ?: return "Error"
        return try {
            val res = when (op) {
                "+" -> a.add(b)
                "โˆ’" -> a.subtract(b)
                "ร—" -> a.multiply(b)
                "รท" -> if (b.compareTo(BigDecimal.ZERO) == 0) return "Cannot รท 0" else a.divide(b, 8, RoundingMode.HALF_UP)
                else -> b
            }
            res.stripTrailingZeros().toPlainString()
        } catch (e: Exception) {
            "Error"
        }
    }

    fun onKey(label: String) {
        when (label) {
            "AC" -> {
                currentInput = "0"
                previousInput = ""
                pendingOp = null
                resetNext = false
            }
            "โŒซ" -> {
                currentInput = if (currentInput.length > 1 && currentInput != "Error") {
                    currentInput.dropLast(1)
                } else "0"
            }
            "ยฑ" -> {
                if (currentInput != "0" && currentInput != "Error") {
                    currentInput = if (currentInput.startsWith("-")) currentInput.drop(1) else "-$currentInput"
                }
            }
            "%" -> {
                val v = currentInput.toBigDecimalOrNull()
                if (v != null) {
                    currentInput = v.divide(BigDecimal(100), 8, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString()
                }
            }
            "+", "โˆ’", "ร—", "รท" -> {
                if (pendingOp != null && !resetNext && previousInput.isNotEmpty()) {
                    val intermediate = compute(previousInput, currentInput, pendingOp!!)
                    currentInput = intermediate
                    previousInput = intermediate
                } else {
                    previousInput = currentInput
                }
                pendingOp = label
                resetNext = true
            }
            "=" -> {
                if (pendingOp != null && previousInput.isNotEmpty()) {
                    val expr = "$previousInput $pendingOp $currentInput"
                    val ans = compute(previousInput, currentInput, pendingOp!!)
                    if (!ans.startsWith("Cannot") && ans != "Error") {
                        history = listOf(expr to ans) + history.take(19)
                    }
                    currentInput = ans
                    previousInput = ""
                    pendingOp = null
                    resetNext = true
                }
            }
            "." -> {
                if (resetNext) {
                    currentInput = "0."
                    resetNext = false
                } else if (!currentInput.contains(".")) {
                    currentInput += "."
                }
            }
            else -> {
                if (currentInput == "0" || resetNext || currentInput.startsWith("Cannot") || currentInput == "Error") {
                    currentInput = label
                    resetNext = false
                } else if (currentInput.length < 15) {
                    currentInput += label
                }
            }
        }
    }

    val rows = listOf(
        listOf("AC", "ยฑ", "%", "รท"),
        listOf("7", "8", "9", "ร—"),
        listOf("4", "5", "6", "โˆ’"),
        listOf("1", "2", "3", "+"),
        listOf("0", ".", "โŒซ", "=")
    )

    Column(
        modifier = Modifier
            .fillMaxSize()
            .statusBarsPadding()
            .navigationBarsPadding()
            .padding(16.dp),
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        // Scrollable History Tape
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .clip(RoundedCornerShape(16.dp))
                .background(Color(0xFF111824))
                .padding(12.dp),
            reverseLayout = true,
            verticalArrangement = Arrangement.spacedBy(6.dp)
        ) {
            items(history) { (expr, ans) ->
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .clickable { currentInput = ans; resetNext = true }
                        .padding(vertical = 4.dp),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(expr, color = Color(0xFF64748B), fontSize = 13.sp)
                    Text("= $ans", color = Color(0xFFFBBF24), fontWeight = FontWeight.SemiBold, fontSize = 14.sp)
                }
            }
        }

        // Readout Display
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp, horizontal = 8.dp),
            horizontalAlignment = Alignment.End
        ) {
            Text(
                text = if (pendingOp != null) "$previousInput $pendingOp" else "",
                color = Color(0xFF94A3B8),
                fontSize = 18.sp
            )
            Text(
                text = currentInput,
                color = Color.White,
                fontSize = if (currentInput.length > 10) 34.sp else 48.sp,
                fontWeight = FontWeight.ExtraBold,
                maxLines = 1,
                overflow = TextOverflow.Ellipsis,
                textAlign = TextAlign.End
            )
        }

        // Keypad Grid
        Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
            rows.forEach { row ->
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    row.forEach { key ->
                        val isOp = key in listOf("รท", "ร—", "โˆ’", "+", "=")
                        val isTop = key in listOf("AC", "ยฑ", "%")
                        val bg = when {
                            key == "=" -> Color(0xFFF59E0B)
                            isOp -> Color(0xFF1E293B)
                            isTop -> Color(0xFF263349)
                            else -> Color(0xFF161F2E)
                        }
                        val fg = when {
                            key == "=" -> Color.Black
                            isOp -> Color(0xFFFBBF24)
                            else -> Color.White
                        }
                        Button(
                            onClick = { onKey(key) },
                            modifier = Modifier
                                .weight(1f)
                                .height(64.dp),
                            shape = RoundedCornerShape(18.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = bg, contentColor = fg)
                        ) {
                            Text(key, fontSize = 22.sp, fontWeight = FontWeight.Bold)
                        }
                    }
                }
            }
        }
    }
}
Troubleshooting

How to Debug Without Losing Your Vibe

When expression parsing or decimal rounding acts up, use these three vibe debugging rules:

The Error Dump Rule

Paste the exact red compiler message from Android Studio's Build tab and ask: "Here is my Gradle build error. Tell me only which imports or types need fixing."

Exact BigDecimal Rule

Never let the LLM use Double for currency or decimal math. Prompt: "Use java.math.BigDecimal with RoundingMode.HALF_UP and stripTrailingZeros() so 0.1 + 0.2 equals 0.3."

Instant Wireless Run

Test keypad ergonomics on your real thumb by pairing your phone over Wi-Fi and using Apply Changes to tweak button heights.

Extensions

The Vibe Prompt Vault

Copy-paste prompts to add scientific functions, full PEMDAS parentheses, and unit converters.

๐Ÿ“ Prompt: Add a Shunting-Yard PEMDAS Expression Evaluator with Parentheses
Prompt Template

"Upgrade my Jetpack Compose Calculator in MainActivity.kt with a pure-Kotlin Shunting-Yard expression parser that supports parentheses ( ), exponents ^, square root โˆš, and full PEMDAS operator precedence while showing a live preview of the result as the user types."

๐Ÿ”„ Prompt: Add a Built-In Unit & Tip Converter Sheet
Prompt Template

"Add a top segmented tab bar to my Compose Calculator switching between 'Calculator', 'Unit Converter' (Length, Weight, Temperature), and 'Bill & Tip Splitter', reusing the current calculator value as the input."

๐Ÿ”Š Prompt: Add Haptic Key Clicks & Copy-on-Long-Press
Prompt Template

"Enhance my Jetpack Compose Calculator buttons with LocalHapticFeedback key-press vibrations, a subtle spring scale animation when pressed, and long-press on the main display readout to copy the result to the system clipboard with a Snackbar confirmation."

We use cookies for ads and analytics.