JavaScripteasyJavaScript

Percentage Calculator

Calculate percentages, discounts, and related values

01

The problem

Need to perform various percentage calculations

02

The solution

JavaScript
const percentage = {
  // Calculate percentage of a number
  of(value, percent) {
    return (value * percent) / 100;
  },
  
  // What percentage is X of Y
  from(part, whole) {
    if (whole === 0) return 0;
    return (part / whole) * 100;
  },
  
  // Calculate percentage change
  change(oldValue, newValue) {
    if (oldValue === 0) return newValue > 0 ? 100 : 0;
    return ((newValue - oldValue) / Math.abs(oldValue)) * 100;
  },
  
  // Add percentage to value
  add(value, percent) {
    return value + this.of(value, percent);
  },
  
  // Subtract percentage from value
  subtract(value, percent) {
    return value - this.of(value, percent);
  },
  
  // Calculate discount
  discount(originalPrice, discountPercent) {
    const discountAmount = this.of(originalPrice, discountPercent);
    return {
      finalPrice: originalPrice - discountAmount,
      discountAmount: discountAmount,
      savingsPercent: discountPercent
    };
  },
  
  // Calculate tax
  tax(amount, taxPercent) {
    const taxAmount = this.of(amount, taxPercent);
    return {
      subtotal: amount,
      taxAmount: taxAmount,
      total: amount + taxAmount,
      taxRate: taxPercent
    };
  },
  
  // Format as percentage string
  format(value, decimals = 2) {
    return `${value.toFixed(decimals)}%`;
  }
};

03

Put it to work

Example
console.log(percentage.of(200, 25)); // 50 (25% of 200)
console.log(percentage.from(50, 200)); // 25 (50 is 25% of 200)
console.log(percentage.change(100, 150)); // 50 (50% increase)
console.log(percentage.add(100, 20)); // 120 (100 + 20%)
console.log(percentage.subtract(100, 20)); // 80 (100 - 20%)

// Discount calculation
const discount = percentage.discount(100, 15);
console.log(discount.finalPrice); // 85
console.log(discount.discountAmount); // 15

// Tax calculation
const tax = percentage.tax(100, 8.25);
console.log(tax.total); // 108.25
console.log(tax.taxAmount); // 8.25

console.log(percentage.format(25.555)); // "25.56%"