Calc OS is a powerful, highly customizable, all-in-one calculator application built specifically for Android. It goes far beyond standard math, offering a complete suite of tools including multi-mode calculators, 15+ converters, global time, a dictionary, and an integrated AI Math Assistant powered by advanced LLM technology.
Wrapped in a beautiful Material Design 3 (Material You) interface, it allows users to deeply personalize their experience with dynamic color palettes, custom Google Fonts, and adjustable button shapes — all while maintaining native performance through a single-file architecture.
- Clean, intuitive everyday calculator with Material 3 design
- Memory Functions: MC (Clear), MR (Recall), M+ (Add), M- (Subtract), MS (Store)
- Infinite History: Never lose a calculation — persistent storage of all operations
- Error Handling: Intelligent division by zero and overflow detection
- Live Display: Real-time expression preview before evaluation
- Advanced Functions:
- Trigonometric: sin, cos, tan with inverse variants (sin⁻¹, cos⁻¹, tan⁻¹)
- Logarithmic: log (base 10), ln (natural log)
- Exponential: e^x, x^y, 10^x
- Root operations: √x, ∛x, custom roots
- Mode Toggle: Seamlessly switch between Degree and Radian modes
- Constants: Quick access to π and e with full precision
- Factorial Support: Direct n! computation
- Multi-Base System: Hex, Dec, Oct, and Bin with instant conversion
- Bitwise Operations: AND, OR, XOR, NOT, Left Shift (LSH), Right Shift (RSH)
- Modulo: MOD operation for remainder calculations
- Base Conversion Display: Real-time value representation across all bases
- Hex Support: Full A-F character input for hexadecimal calculations
- Length: Millimeters, Centimeters, Meters, Kilometers, Inches, Feet, Yards, Miles, Nautical Miles
- Weight/Mass: Milligrams, Grams, Kilograms, Ounces, Pounds, Tons, Metric Tons
- Volume: Milliliters, Liters, Cubic Meters, Fluid Ounces, Cups, Pints, Quarts, Gallons
- Area: Square Millimeters, Square Meters, Square Kilometers, Acres, Hectares, Square Feet, Square Miles
- Temperature: Celsius, Fahrenheit, Kelvin with accurate conversion formulas
- Data Storage: Bytes, KB, MB, GB, TB, PB with binary (1024-based) calculations
- Speed: m/s, km/h, mph, knots, feet/second
- Time: Seconds, Minutes, Hours, Days, Weeks, Months, Years
- Angle: Degrees, Radians, Gradians
- Pressure: Pascal, Bar, Atmosphere, PSI, Torr
- Energy: Joules, Kilojoules, Calories, Kilocalories, Watt-hours, Kilowatt-hours
- Power: Watts, Kilowatts, Megawatts, Horsepower
- Force: Newtons, Kilonewtons, Pounds-force, Kilograms-force
- Data Rate: bps, Kbps, Mbps, Gbps, KBps, MBps, GBps
- Real-Time Exchange Rates: Fetches current fiat currency rates via Fawazahmed0 Currency API
- Major Currencies: USD, EUR, GBP, JPY, CNY, INR, PKR, AUD, CAD, CHF, and 100+ more
- Crypto Support: Bitcoin (BTC), Ethereum (ETH), Solana (SOL), and other major cryptocurrencies
- Auto-Refresh: Intelligent caching with periodic rate updates
- Offline Fallback: Graceful handling when network is unavailable
- Loan/Mortgage Calculator:
- Principal amount, interest rate, and term inputs
- Monthly payment estimation with compound interest
- Total interest paid over loan lifetime
- Amortization breakdown
- Formula: Uses standard annuity formula with error handling for edge cases
- BMI (Body Mass Index):
- Metric units: kg and cm
- Imperial units: lbs and inches
- BMI categories: Underweight, Normal, Overweight, Obese (WHO standards)
- Real-time category display with color coding
- Precise Date Difference:
- Calculate years, months, and days between any two dates
- Leap year handling
- Timezone-aware calculations
- Clear output format: "X years, Y months, Z days"
- Context-Aware Conversations:
- Maintains last 20 message pairs (40 total messages)
- Persistent localStorage chat history across sessions
- Clear chat option to reset memory
- Mathematical Expertise:
- Custom system prompt: "You are a highly capable Math AI Assistant created by Muhammad Awais & Ehsar at HyBox Studio"
- Optimized for K-12 and college-level mathematics
- Step-by-step explanations in simple language
- LLM Backend: Powered by PicoApps LLM API with encrypted endpoint
- KaTeX Integration:
- Flawless LaTeX rendering for complex equations
- Block math:
$$...$$or\[...\] - Inline math:
$...$or\(...\) - Automatic delimiter detection
- Markdown Support:
- Full GitHub Flavored Markdown via Marked.js
- Lists, tables, code blocks, headers
- Math-aware parsing prevents conflicts
- Safe Rendering Pipeline:
1. Extract all math blocks → Store safely 2. Parse markdown on text 3. Restore math blocks → Render with KaTeX
- Bubble-Free Interface: Modern professional chat layout without speech bubbles
- Custom AI Avatar: DiceBear Avataaars API (seed: "Aiden274")
- Smooth Animations: Auto-scroll to latest message with smooth behavior
- Loading States: Animated spinner during API calls
- Error Handling: Network error messages with retry guidance
- Free Dictionary API integration
- Instant word definitions for mathematical terms and general vocabulary
- No API key required
- Displays: definitions, parts of speech, phonetics, and example usage
- Error handling for words not found
- WorldTimeAPI.org integration
- Accurate global time lookup for any timezone
- Returns: current datetime, timezone abbreviation, UTC offset, day of week
- Useful for international collaboration and time zone conversions
- 13-Color Material 3 Palette Generator:
- Input: Single HEX color (e.g.,
#6750A4) - Output: Complete light + dark theme with all semantic tokens
- Generated colors:
- Primary, Secondary, Tertiary (+ Container variants)
- Error, Background, Surface
- Outline, OutlineVariant, OnSurface variants
- Input: Single HEX color (e.g.,
- Algorithm: Custom JavaScript implementation of Material Design 3 color science
- Live Preview: Colors update instantly across entire app
- Presets: Purple, Blue, Green, Red, Teal with one-tap apply
- Google Fonts Integration:
- Import any font via direct Google Fonts URL
- Example:
https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap
- Font Pills: Save multiple fonts as reusable "pills"
- Granular Control:
- Global Font: Applied app-wide (body, buttons, labels)
- Calculator Display: Specific font for calc output (e.g., monospace)
- AI Chat: Custom font for AI message bubbles
- Font Weights: Automatic multi-weight support (400, 500, 600)
- Pill (Circular): Fully rounded buttons (
rounded-full) - Rounded Rectangle (Squircle): Balanced 16px radius (
rounded-2xl) - Square: Sharp corners (
rounded-sm) - Instant Application: Changes reflect immediately without reload
- Dark/Light Mode:
- Manual toggle or system preference sync
- Persistent preference storage
- Smooth color transitions
- All Material 3 tokens switch automatically
- All customizations stored in
localStorage - Survives app restarts and reinstalls (if localStorage intact)
- Settings keys:
calcosColor— Base colorcalcosButtonStyle— Shape preferencecalcosFontGlobal,calcosFontCalc,calcosFontAI— TypographycalcosSavedFonts— Font pills array
- Total calculations performed
- Scientific function usage count
- AI queries submitted
- Converter usage frequency
- Session duration tracking
- View all-time usage stats
- Clean visual cards with icons
- Real-time updates
- Reset option available
Frontend Framework
- Vanilla JavaScript ES6+ (Zero frameworks, pure performance)
- HTML5 with semantic markup
- Tailwind CSS v3.4+ via CDN with custom Material 3 config
UI Components
- Lucide Icons: Complete icon system (600+ icons)
- Custom Material 3 elevation system (shadow-md3-1, shadow-md3-2, shadow-md3-3)
- CSS Grid & Flexbox for responsive layouts
Mathematical Libraries
- KaTeX v0.16.9: LaTeX math rendering
- Marked.js: Markdown parser (GitHub Flavored Markdown)
- Native JavaScript Math API for calculations
External APIs
1. PicoApps LLM API (Encrypted): AI Math Assistant backend
2. Fawazahmed0 Currency API: Live currency & crypto rates
3. WorldTimeAPI.org: Global time data
4. Free Dictionary API: Word definitions
5. DiceBear Avataaars API: AI avatar generation
State Management
// Global state object
const state = {
view: 'standard' | 'scientific' | 'programmer',
display: '0',
memory: '0',
expression: '',
degMode: true,
progBase: 10 | 16 | 8 | 2,
history: [],
// ... + 15 converter states
};Storage Architecture
localStorage Keys:
- calcosHistory: Calculation history array (max 100 items)
- calcosColor: Base theme color (HEX)
- calcosButtonStyle: 'pill' | 'rounded' | 'square'
- calcosFontGlobal: Global font family
- calcosFontCalc: Calculator display font
- calcosFontAI: AI chat font
- calcosSavedFonts: Array of saved font URLs
- calcosStats: Usage statistics object
- aiMathAssistant: AI chat history (last 40 messages)
Why Single-File?
- Zero Dependencies: No build process, no npm, no webpack
- Instant Deployment: Drop HTML → Convert → APK
- Performance: No HTTP requests for assets (all inline)
- Simplicity: 1 file = easier maintenance and debugging
- APK Conversion: HTML-to-APK tools work best with single files
File Structure (Internal Organization)
<!DOCTYPE html>
├── <head>
│ ├── Meta tags (viewport, charset)
│ ├── Tailwind CSS CDN + Custom MD3 Config
│ ├── External CDN Libraries (Lucide, Marked, KaTeX)
│ └── <style> Material 3 CSS Variables + Custom Styles
├── <body>
│ ├── App Container (Main Layout)
│ ├── Bottom Navigation Bar
│ ├── Calculator Views (Standard, Scientific, Programmer)
│ ├── Toolkit Screens (Converters, Financial, Health, Date)
│ ├── AI Math Assistant Interface
│ ├── Dictionary & Time APIs
│ ├── Settings Modal with Color/Font/Shape Pickers
│ └── <script> Full Application Logic (~1100 lines)
└── </html>// Simplified version of the algorithm
function generateMD3Palette(baseHex) {
const rgb = hexToRGB(baseHex);
const hsl = rgbToHSL(rgb);
// Generate palette based on HSL transformations
return {
primary: baseHex,
primaryContainer: lighten(hsl, 90),
secondary: rotateHue(hsl, 30),
tertiary: rotateHue(hsl, 60),
error: '#B3261E',
surface: determineSurface(hsl),
// ... 13 total colors with light/dark variants
};
}function evaluateExpression(expr) {
try {
// Sanitize input
expr = expr.replace(/×/g, '*').replace(/÷/g, '/');
// Handle special functions (√, π, e, etc.)
expr = expr.replace(/√(\d+)/g, 'Math.sqrt($1)');
expr = expr.replace(/π/g, 'Math.PI');
// Safe eval with Function constructor
const result = Function(`"use strict"; return (${expr})`)();
return result;
} catch (e) {
return 'Error';
}
}function saveAIChatHistory(content, isUser) {
const chats = JSON.parse(localStorage.getItem('aiMathAssistant') || '[]');
chats.push({ content, isUser, timestamp: Date.now() });
// Keep only last 40 messages (20 pairs)
if (chats.length > 40) {
chats.splice(0, chats.length - 40);
}
localStorage.setItem('aiMathAssistant', JSON.stringify(chats));
}async function fetchCurrencyRates(fromCurrency, toCurrency) {
const url = `https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/${fromCurrency}.json`;
try {
const response = await fetch(url);
const data = await response.json();
return data[fromCurrency][toCurrency];
} catch (error) {
// Fallback to cached rates if available
return getCachedRate(fromCurrency, toCurrency);
}
}- Lazy Loading: AI assistant components only initialize when first accessed
- Debounced Inputs: Currency/converter inputs debounced by 300ms
- Smart Caching: Currency rates cached for 1 hour to minimize API calls
- Event Delegation: Single event listener for calculator buttons (not per-button)
- LocalStorage Throttling: History saves throttled to prevent excessive writes
- CSS Containment:
contain: layout styleon major sections - Virtual Scrolling: History limited to last 100 items
- Keyboard Navigation:
- Full keyboard support (0-9, operators, Enter for equals, Escape for clear)
- Hex characters (A-F) in programmer mode
- Tab navigation through all interactive elements
- Screen Reader Support:
- Semantic HTML5 elements (
<nav>,<main>,<button>) - ARIA labels on icon-only buttons
- Live regions for calculation results
- Semantic HTML5 elements (
- High Contrast Mode: Respects system prefers-contrast settings
- Focus Indicators: Visible focus rings on all interactive elements
- Touch Targets: All buttons minimum 44×44px (WCAG AAA)
-
Download APK:
- Go to Releases tab
- Download latest
CalcOS.apk(v1.0+)
-
Install on Android:
Settings → Security → Enable "Install from Unknown Sources" Open CalcOS.apk → Install → Open -
Permissions Required:
- Internet (for AI, currency, dictionary, time APIs)
- Storage (optional, for future backup feature)
# No installation needed!
# Just open index.html in any modern browser
open index.html
# Or start a local server
python -m http.server 8000
# Navigate to http://localhost:8000# Using Website 2 APK Builder Pro (Recommended)
1. Visit: https://websitetoapk.com or similar tool
2. Upload index.html
3. Configure:
- App Name: Calc OS
- Package Name: com.hybox.calcos
- Icon: Upload 512x512 PNG
- Orientation: Portrait
- Status Bar: Hidden
4. Build APK → Download
# Alternative: Android Studio WebView Wrapper
1. Create new Android Studio project
2. Add WebView to MainActivity
3. Place index.html in assets/
4. Load file:///android_asset/index.html
5. Build → Generate Signed APK// Add to index.html <head>
<link rel="manifest" href="manifest.json">
<meta name="theme-color" content="#6750A4">
// manifest.json
{
"name": "Calc OS",
"short_name": "Calc OS",
"start_url": "/",
"display": "standalone",
"background_color": "#FFFBFE",
"theme_color": "#6750A4",
"icons": [/* icon definitions */]
}- ✅ Android 8.0+ (API 26+)
- ✅ Chrome/Chromium WebView
- ✅ Desktop Browsers: Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
- ✅ Screen Sizes: 4" phones to 10" tablets
- Calculator Logic: 100+ unit test scenarios
- Converters: Verified against Google/WolframAlpha
- AI Rendering: Tested with 50+ complex LaTeX equations
- Theme System: All 5 presets + 100+ custom colors tested
- Accessibility: Lighthouse score 95+
- AI Assistant: Requires internet connection (no offline mode)
- Currency Rates: Dependent on Fawazahmed0 API uptime
- Memory Limits: History capped at 100 items, AI chat at 40 messages
- Browser Requirements: ES6+ support mandatory (no IE11)
For Students:
- Practical math tool for homework and exams
- AI tutor explains step-by-step solutions
- Understand unit conversions visually
- Learn LaTeX formatting through AI examples
For Developers:
- Single-file SPA architecture pattern
- Material Design 3 implementation from scratch
- State management without frameworks
- API integration best practices
- KaTeX + Markdown rendering pipeline
- LocalStorage patterns for complex data
- CS Education: Teach web development fundamentals
- UI/UX Design: Material 3 reference implementation
- Math Apps: Fork and extend for specialized domains
- PWA Examples: Demonstrate offline-first techniques
We welcome contributions! Here's how to get involved:
- 🐛 Report Bugs: Open an issue with repro steps
- ✨ Request Features: Suggest new converters, calculators, or UI improvements
- 📝 Improve Docs: Fix typos, add examples, clarify instructions
- 💻 Submit Code: PRs for bug fixes or new features
# 1. Fork & clone
git clone https://github.com/YOUR_USERNAME/calc-os.git
cd calc-os
# 2. Create feature branch
git checkout -b feature/amazing-feature
# 3. Make changes to index.html
# 4. Test thoroughly (all calculator modes, AI, converters)
# 5. Commit with clear message
git commit -m "Add: Scientific notation support"
# 6. Push & open PR
git push origin feature/amazing-feature// Use descriptive variable names
const userInputValue = document.getElementById('input').value; // ✅
const uiv = document.getElementById('input').value; // ❌
// Comment complex logic
// Parse markdown first, then restore math blocks to prevent conflicts
const html = marked.parse(processedText);
// Use ES6+ features
const result = numbers.map(n => n * 2); // ✅
const result = numbers.map(function(n) { return n * 2; }); // ❌ (verbose)
// Handle errors gracefully
try {
const data = await fetchAPI();
} catch (error) {
showToast('Network error. Please retry.');
}- Tested on Android device/emulator
- Tested in Chrome, Firefox, Safari
- No console errors
- Follows existing code style
- Updated README if adding features
- Accessible (keyboard nav, screen readers)
- Dark mode works correctly
- Graphing calculator with Plotly.js
- Matrix operations (add, multiply, determinant)
- Equation solver (linear, quadratic, systems)
- Export calculations to PDF
- Cloud backup with Google Drive sync
- Chemistry calculator (molar mass, stoichiometry)
- Physics calculator (kinematics, forces)
- Statistics mode (mean, median, std dev, regression)
- Custom themes import/export
- Widget for Android home screen
- Offline AI mode with TensorFlow.js
- Voice input for calculations
- Handwriting recognition
- Multi-user profiles
- Adaptive learning (personalized AI responses)
- AR calculator (overlay on real-world objects)
- Collaborative mode (shared calculations)
- Gesture shortcuts (swipe patterns for functions)
- Themes marketplace
// Perform calculation
handleCalcInput(value: string) → void
// Evaluate expression
evaluateExpression(expr: string) → string | number
// Memory operations
memoryStore() → void
memoryRecall() → void
memoryAdd() → void
memorySubtract() → void
memoryClear() → void
// History management
addToHistory(expression: string, result: string) → void
getHistory() → Array<{expr: string, result: string, timestamp: number}>
clearHistory() → void// Generic converter
convertUnit(value: number, fromUnit: string, toUnit: string, category: string) → number
// Currency converter (async)
convertCurrency(amount: number, from: string, to: string) → Promise<number>
// Date difference
calculateDateDiff(startDate: Date, endDate: Date) → {years: number, months: number, days: number}
// BMI calculator
calculateBMI(weight: number, height: number, isMetric: boolean) → {bmi: number, category: string}// Set base color (generates full palette)
setBaseColor(hexColor: string) → void
// Apply saved theme
applyTheme(colorObject: Object) → void
// Toggle dark mode
toggleDarkMode() → void
// Get current theme
getCurrentTheme() → 'light' | 'dark'// Send message to AI
sendAIMessage(prompt: string) → Promise<string>
// Get chat history
getAIChatHistory() → Array<{content: string, isUser: boolean, timestamp: number}>
// Clear chat
clearAIChat() → void
// Render markdown + math
parseMarkdownAndMathSafe(text: string) → string (HTML)POST https://backend.buildpicoapps.com/aero/run/llm-api
Content-Type: application/json
Authorization: pk=v1-[ENCRYPTED_KEY]
{
"prompt": "Full conversation context + user query"
}
Response:
{
"status": "success",
"text": "AI response with markdown and LaTeX"
}GET https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/usd.json
Response:
{
"date": "2024-03-15",
"usd": {
"eur": 0.92,
"gbp": 0.79,
"btc": 0.000015,
...
}
}GET http://worldtimeapi.org/api/timezone/America/New_York
Response:
{
"datetime": "2024-03-15T14:30:00.123456-04:00",
"timezone": "America/New_York",
"abbreviation": "EDT",
"utc_offset": "-04:00",
...
}GET https://api.dictionaryapi.dev/api/v2/entries/en/calculator
Response:
[{
"word": "calculator",
"phonetic": "/ˈkælkjʊleɪtə/",
"meanings": [{
"partOfSpeech": "noun",
"definitions": [{
"definition": "An electronic device for mathematical calculations"
}]
}]
}]- Local-First: All user data stored in browser localStorage (never server)
- No Tracking: Zero analytics, no cookies, no fingerprinting
- API Keys: Encrypted in code (public APIs with free tier)
- HTTPS Only: All external API calls over secure connections
- No Account Required: Fully functional without registration
- No Personal Data Collection: App doesn't ask for name, email, location
- Chat History: Stored locally, never uploaded to servers
- Offline Capable: Core calculator works without internet
- API Key Rotation: Consider rotating PicoApps key periodically
- Self-Host APIs: Fork Fawazahmed0/Dictionary APIs for full control
- Content Security Policy: Add CSP headers when self-hosting
- Rate Limiting: Implement client-side throttling for API calls
This project is licensed under the MIT License - see the LICENSE file for detai
MIT License
Copyright (c) 2026 HyBox
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Muhammad Awais & Sawera Ehsar
HyBox Studio
- Tailwind CSS - Utility-first CSS framework
- KaTeX - Fast math rendering library
- Marked.js - Markdown parser
- Lucide - Beautiful icon system
- Material Design 3 - Google's design system
- Fawazahmed0 Currency API - Free currency data
- WorldTimeAPI - Timezone information
- Free Dictionary API - Word definitions
- DiceBear - Avatar generation
- PicoApps - LLM API platform
- Material Design team for comprehensive design guidelines
- Open source community for free APIs and libraries
- Beta testers for valuable feedback
- 🌐 Website: HyBox
- 📧 Email: [email protected]
If you find Calc OS helpful, consider:
- ⭐ Star this repo to help others discover it
- 🔄 Share with friends who need a powerful calculator
- 📝 Write a blog post about your experience
If you'd like to support my development work, feel free to contribute through any of these platforms:
0xc26f066E2ec5822a5508Ae0455CCA0A236B620d3
- Lines of Code: ~1350 (HTML + CSS + JS in one file)
- File Size: ~85KB uncompressed, ~25KB gzipped
- Development Time: 3 weeks of intense coding
- Coffee Consumed: ∞ cups ☕
- Bugs Fixed: 142 (and counting)
- API Calls Tested: 10,000+
- Color Combinations Tried: 237
Made with ❤️ and ∞ precision
Calc OS - Where Material Design Meets Mathematical Excellence
Features • Architecture • Install • API Docs • Contribute • License





